Sub topic 7
Controlling Access to Object State
A class is a definition for making objects. An object is one item made from a class. A field is a variable that belongs to an object. Together, its fields hold its state: the information the object stores.
A method is a named set of instructions that can read or change that state. For example, a lamp object might have a field that records whether the lamp is on. It might also have methods for turning the lamp on and off.
Who should be able to change that field? Java lets a class control access to its members. A member is a field or method that belongs to a class.
This control matters because it lets a class decide how other code uses its objects. Other code can ask a lamp to turn on without needing to know exactly how the lamp stores its state.
Public and private
An access modifier is a Java keyword that controls where a class or member can be used. Two common access modifiers are public and private.
| Modifier | Access |
|---|---|
| `public` | Code in other classes can use the member, as long as the class itself is accessible there. |
| `private` | Code outside the class that declares the member cannot use it directly. |
For example, a lamp class can make its on field private and its turnOn method public. Other classes can call turnOn, but they cannot directly change on.
Keeping state behind methods is part of encapsulation. Encapsulation means keeping an object’s data and the operations on that data together, while controlling access to them.
The methods a class makes available to other code form part of its public interface. The public interface says what callers can ask the object to do. It does not need to reveal every detail of how the object works.
A worked example
This program creates two lamps. Each lamp keeps its own on-or-off state in a private field.
Save the code in a file named LampDemo.java.
public class LampDemo {
public static void main(String[] args) {
ReadingLamp deskLamp = new ReadingLamp();
ReadingLamp floorLamp = new ReadingLamp();
System.out.println("Desk on: " + deskLamp.isOn());
deskLamp.turnOn();
System.out.println("Desk: " + deskLamp.describe());
System.out.println("Floor on: " + floorLamp.isOn());
deskLamp.turnOff();
System.out.println("Desk on: " + deskLamp.isOn());
}
}
class ReadingLamp {
private boolean on = false;
public void turnOn() {
on = true;
}
public void turnOff() {
on = false;
}
public boolean isOn() {
return on;
}
public String describe() {
return "Lamp is " + stateText();
}
private String stateText() {
if (on) {
return "on";
}
return "off";
}
}To compile a Java program is to turn its source code into a form Java can run. Open a terminal in the folder containing the file. Run javac LampDemo.java, then run java LampDemo.
The output is:
Desk on: falseDesk: Lamp is onFloor on: falseDesk on: false
Follow the example
The main method is where Java starts this program. It creates deskLamp and floorLamp. Each object has its own on field, and each field starts as false.
The field has the type boolean, which can hold either true or false. The word private before the field means that code in LampDemo cannot use the field directly.
The program calls deskLamp.isOn() to read the lamp’s state. The method is public, so LampDemo can call it. The method returns false.
Next, the program calls deskLamp.turnOn(). That public method runs inside the ReadingLamp class, so it can change the private on field. The call changes only the desk lamp. The floor lamp stays off.
Finally, deskLamp.turnOff() changes the desk lamp’s field back to false.
Try adding deskLamp.on = true; inside main, then compile the program again. Java reports an error because on is private to ReadingLamp. Remove that line before running the program again.
Reading state with an accessor
An accessor is a method that provides information about an object. An accessor is often called a getter.
The lamp’s isOn method is an accessor. It reads the private field and returns its value:
deskLamp.isOn()
Callers learn whether the lamp is on without accessing the on field themselves. For a true-or-false result, names that begin with is, such as isOn, are common in Java.
An accessor can also return a result made from state. In the example, describe returns the text Lamp is on or Lamp is off. Callers do not need to know how that text is built.
A class does not have to provide an accessor for every private field. Expose information that callers need, and keep other details inside the class.
Changing state with a method
A mutator is a method that changes an object’s state. The turnOn and turnOff methods are mutators. Their names describe the actions a caller wants to take.
A mutator that accepts a value and sets a field is often called a setter. For example, a lamp class could offer a method named setOn that takes a boolean. This example uses two action names instead: turnOn and turnOff.
A private field with a public setter can still be changed by other code. The difference is that the change goes through a method. That gives the class one place to manage what the change does.
Not every private field needs a public setter. For some information, callers may need to read a value but should not be able to change it through the public interface.
Private methods hide details too
Fields are not the only members that can be private. A class can also have private methods.
In the example, stateText is private. The public describe method calls it to get the word on or off. Code in LampDemo can call describe, but it cannot call deskLamp.stateText().
A private method is useful for work that supports the class but is not an action callers need. The class can change that helper later without asking callers to change how they use describe.
Why not make every field public?
If on were public, code outside ReadingLamp could read or assign it directly. That might seem simpler for a small example. But other code would then depend on that field and its name.
With a private field, callers depend on methods such as isOn and turnOn instead. The class has more freedom to change how it stores the lamp’s state, while keeping those methods available.
Encapsulation also helps a reader find where changes happen. To see how a lamp is turned on, look at turnOn. To see how the state is reported, look at isOn or describe.
Private fields do not make a class correct by themselves. The methods inside the class must still use those fields carefully. Access control defines who can reach a member directly; it does not guarantee that every method behaves as intended.
Classes have access levels too
Access modifiers can apply to classes as well as their members. A package is a way to group Java classes.
In the example, LampDemo is public. ReadingLamp has no access modifier, so it has package access: other classes in the same package can use it. Both classes in the example are in the same package.
Even though the lamp’s methods are public, another class must be able to access ReadingLamp before it can use those methods. For a lamp class used from other packages, you could declare ReadingLamp public in its own file, named ReadingLamp.java.
A note about returned data
The lamp’s isOn method returns a boolean value. Changing a caller’s own boolean variable cannot change the lamp’s field.
Other kinds of data need more care. For example, an array is an object that holds a sequence of values. If an accessor returns an object’s private array, a caller can change the array’s contents. The field is private, but the returned array is still shared.
If callers only need to inspect such data, a class can return a copy instead. The right choice depends on whether callers should be able to affect the original data.
Practice
Exercise
Why can LampDemo call deskLamp.turnOn() but not assign deskLamp.on directly?
Show answer
turnOn is public. The on field is private to ReadingLamp, so code in LampDemo cannot access it directly.
Exercise
If deskLamp is turned on, does that also turn floorLamp on? Why?
Show answer
No. Each ReadingLamp object has its own on field. The call changes the field in deskLamp only.
Exercise
Add a public toggle method inside ReadingLamp. What statement could it use to switch on to off and off to on?
Show answer
The statement on = !on; switches the boolean value. The ! operator changes true to false and false to true.
Exercise
Does making a field private mean the class must provide a public getter and setter for it?
Show answer
No. The class should expose only the information and actions that callers need.