Access, Visibility, and Encapsulation
The anatomy of a class, how the keywords public and private control which code can use each part, and why keeping instance variables private, encapsulation, makes classes safer and easier to change.
Data encapsulation is a technique in which the implementation details of a class are kept hidden from external classes. The keywords public and private affect the access of classes, data, constructors, and methods: private restricts access to the declaring class, while public allows access from classes outside it. Classes and constructors are designated public. Instance variables belong to the object, each object having its own copy, and are designated private unless a specification says otherwise. Methods may be public, for use by other classes, or private, for use only inside the class.
1Anatomy of a Class
A class definition begins with a header, public class Speaker, followed by a body in braces. Classes written here are always designated public and are declared with the keyword class. Inside the body come three kinds of members: instance variables, which hold each object's attributes; constructors, which set up new objects; and methods, which define the object's behaviors.
By convention, instance variables are declared first, at the top of the class body and outside every method and constructor, followed by constructors and then methods. Constructors are designated public, since other classes must be able to create objects. Reading a class in this order answers three questions in turn: what does each object know, how is it created, and what can it do?
public and private decide which parts other classes may use.| Part of a class | Usual access | Why |
|---|---|---|
| The class itself | public class Name | Other classes need to create and use its objects |
| Constructors | public | Other classes must be able to create objects |
| Instance variables | private | Keeps attributes internal: encapsulation |
| Methods other classes call | public | They form the class's interface |
| Helper methods | private | Implementation details used only inside the class |
2public and private
The keywords public and private are access modifiers. The keyword private restricts access to the declaring class: a private instance variable or method can be used only by code written inside that same class. The keyword public allows access from classes outside the declaring class, so any other class can use the member through an object or the class name.
Access is checked by the compiler. A statement in another class that names a private member does not compile, and the error message says that the member "has private access." This makes access rules a design tool: by choosing which members are public, the author of a class decides exactly how other code is allowed to interact with its objects.
Access is decided per class, not per object. Code inside the Speaker class can use the private members of any Speaker object, not only the one whose method is running. What private blocks is code written in other classes, such as a Main class that creates and uses speakers.
| Attempt from another class | Result |
|---|---|
new Speaker("Porch") | Allowed: public constructor |
s.getVolume() | Allowed: public method |
s.volume | Compile error: volume has private access |
s.clamp(42) | Compile error: clamp has private access |
Classifying Each Member
For the Speaker class above, state which members another class may use.
- 1Usable from outside (public): the constructor
Speaker(String), and the methodsgetName,getVolume,setVolume, andlouder. - 2Usable only inside (private): the instance variables
nameandvolume, and the helper methodclamp. - 3The class itself is declared
public class Speaker, so other classes may create and useSpeakerobjects.
3Private Instance Variables
Instance variables belong to the object, and each object has its own copy of the variable. A Speaker named "Kitchen" and one named "Garage" each store their own name and volume, and changing one does not affect the other.
Access to attributes should be kept internal to the class in order to accomplish encapsulation. Therefore, it is good programming practice to designate the instance variables for these attributes as private unless the class specification states otherwise. Other classes then read and change an object's data only through the methods the class provides, which can check and enforce rules about valid values.
The methods that read and change private data are usually small and predictable: an accessor such as getVolume returns a copy of a value, and a mutator such as setVolume changes it, applying any rules on the way. A class does not need a mutator for every attribute; leaving one out, as Speaker does for name, makes that attribute unchangeable from outside once the object is created.
private restricts access to the declaring class, while public allows access from classes outside it.Two Speakers, Two Volumes
Predict the output.
public class Speaker
{
private String name;
private int volume;
public Speaker(String n)
{
name = n;
volume = 5;
}
public String getName()
{
return name;
}
public int getVolume()
{
return volume;
}
public void setVolume(int v)
{
volume = clamp(v);
}
public void louder()
{
setVolume(volume + 1);
}
private int clamp(int v)
{
if (v < 0)
{
return 0;
}
if (v > 10)
{
return 10;
}
return v;
}
}
Kitchen 9
Garage 6
- 1Instance variables belong to the object.
aandbeach have their ownnameandvolume. - 2
a.setVolume(9)affects onlya;b.louder()raises onlybfrom 5 to 6.
Reaching Past the Methods
Explain the compile error.
public class Speaker
{
private String name;
private int volume;
public Speaker(String n)
{
name = n;
volume = 5;
}
public String getName()
{
return name;
}
public int getVolume()
{
return volume;
}
public void setVolume(int v)
{
volume = clamp(v);
}
public void louder()
{
setVolume(volume + 1);
}
private int clamp(int v)
{
if (v < 0)
{
return 0;
}
if (v > 10)
{
return 10;
}
return v;
}
}
- 1
volumeis private. It can be used only inside theSpeakerclass. - 2Main is another class, so the compiler reports that
volumehas private access inSpeaker. - 3Fix. Use the public method:
s.setVolume(15);, which also applies the 0-to-10 rule.
A public instance variable lets any class set it to anything, including values that break the object's rules, such as a volume of 15 or −3. Keep instance variables private and provide methods that change them safely.
4Public and Private Methods
Access to behaviors can be internal or external to the class. Methods designated as public can be accessed internally or externally to a class, whereas methods designated as private can only be accessed internally to the class. Public methods form the class's interface, the set of operations other code relies on.
Private methods are helpers. When a public method contains a step that is useful on its own, or that several methods share, the step can be extracted into a private method, such as clamp. Because no other class can call it, a private helper can be changed, renamed, or removed freely, as long as the public methods still behave the same.
Working Through the Public Interface
The Speaker class is given. Predict the output.
public class Speaker
{
private String name;
private int volume;
public Speaker(String n)
{
name = n;
volume = 5;
}
public String getName()
{
return name;
}
public int getVolume()
{
return volume;
}
public void setVolume(int v)
{
volume = clamp(v);
}
public void louder()
{
setVolume(volume + 1);
}
private int clamp(int v)
{
if (v < 0)
{
return 0;
}
if (v > 10)
{
return 10;
}
return v;
}
}
Porch 7
10
0
- 1Constructor. Volume starts at 5; two calls to
louderraise it to 7. - 2
setVolume(15). The private helperclamplimits it to 10. - 3
setVolume(-3). Clamped to 0. - 4Main never touches
volumedirectly; every change goes through public methods.
A Helper Only the Class May Call
Explain the compile error.
public class Speaker
{
private String name;
private int volume;
public Speaker(String n)
{
name = n;
volume = 5;
}
public String getName()
{
return name;
}
public int getVolume()
{
return volume;
}
public void setVolume(int v)
{
volume = clamp(v);
}
public void louder()
{
setVolume(volume + 1);
}
private int clamp(int v)
{
if (v < 0)
{
return 0;
}
if (v > 10)
{
return 10;
}
return v;
}
}
- 1
clampis private.setVolumecalls it internally, but other classes cannot. - 2Why private.
clampis an implementation detail; keeping it private means it can be changed or removed without affecting any other class.
A private method is invisible outside its class. If code in another class needs that behavior, the class should offer a public method that provides it, usually one that uses the helper internally.
5Why Encapsulate?
Encapsulation means that a class's implementation details, its instance variables and helper methods, are kept hidden from external classes. Two benefits follow. First, the class can guarantee that its objects are always valid, because every change passes through its own methods. Second, the class's author can change how the class works internally without breaking other code, as long as the public methods keep their signatures and behavior.
Encapsulation also makes programs easier to understand and debug. Users of a class need to learn only its public methods, and if an object's data is ever wrong, the cause must be in the class's own code, because nothing else could have changed it. These benefits grow with the size of the program and the number of people working on it.
volume is private, every change goes through methods that keep it valid.| Benefit of encapsulation | Example |
|---|---|
| Protects valid state | Volume always stays between 0 and 10 |
| Allows internal changes | Rewrite a private helper without touching other classes |
| Simplifies use | Users learn a few public methods, not the internals |
| Localizes errors | Only the class's own code can change its data |
Changing the Inside Without Breaking the Outside
The class's author replaces the private helper with a different implementation. Does the calling code need to change?
public class Dial
{
private int level;
public Dial()
{
level = 0;
}
public void turn(int steps)
{
level = wrap(level + steps);
}
public int getLevel()
{
return level;
}
private int wrap(int v)
{
return v % 12;
}
}
2
- 1The public interface is just
turnandgetLevel. - 2Trace. 0 + 5 = 5; then 5 + 9 = 14, and
14 % 12= 2. - 3Freedom to change. Because
wrapandlevelare private, the author could store the level differently or rewritewrapentirely; as long asturnandgetLevelbehave the same, no other class needs to change.
Encapsulation is about what users depend on. A public method named for an internal detail, such as getClampResult, ties other code to how the class works. Name public methods for what they do for the user, such as setVolume.
6Reading and Writing Classes
When reading a class, start with its public members: they say what the class offers. Then read the private instance variables to see what each object stores, and finally the method bodies to see how the behaviors work. When writing a class, follow the conventions in this guide: a public class, public constructors, private instance variables, public methods for the interface, and private helper methods for internal steps.
Access modifiers apply to members of a class. Local variables declared inside a method or constructor, including parameters, never take public or private; they exist only while the method runs and are already invisible to every other class.
private int total = 0; written inside a method does not compile. Only class members, meaning instance variables, class variables, constructors, and methods, take access modifiers. Local variables are declared with just a type and a name.
Four Habits for Encapsulated Classes
1. public Class, public Constructors
So other classes can create objects.
2. private Instance Variables
Change data only through methods.
3. public Interface, private Helpers
Expose what users need; hide the rest.
4. Each Object, Its Own Copy
Private limits access, not the number of copies.
Data encapsulation is a technique in which the implementation details of a class are kept hidden from external classes. The keywords public and private affect the access of classes, data, constructors, and methods: private restricts access to the declaring class, while public allows access from classes outside it. Classes are designated public and declared with the keyword class, and constructors are designated public. Instance variables belong to the object, each object having its own copy, and should be designated private unless the class specification states otherwise. Public methods can be accessed internally or externally to a class, whereas private methods can only be accessed internally.