Encapsulation and Information Hiding
Encapsulation: Guarding an Object's State
Once you can write a class with fields and methods, the next question is who should be allowed to change those fields. Many objects have rules their data must follow: a bank balance that never goes negative, a battery charge between 0 and 100 percent, a month between 1 and 12. This lesson shows how a class protects those rules itself, so that no other part of the program can break them by accident.
Bundling data with the methods that guard it
Encapsulation is the practice of bundling an object's data with the methods that operate on it, and letting outside code reach that data only through those methods. In Java this usually means declaring fields private and providing public methods for the operations other classes genuinely need. The client code then works with what an object does, not with how it stores its data. Keeping those storage details out of view is often called information hiding.
public class Battery {
private int percent;
public Battery(int startPercent) {
percent = clamp(startPercent);
}
public void charge(int amount) {
if (amount > 0) {
percent += Math.min(amount, 100 - percent);
}
}
public void drain(int amount) {
if (amount > 0) {
percent -= Math.min(amount, percent);
}
}
public int getPercent() {
return percent;
}
private int clamp(int value) {
return Math.max(0, Math.min(100, value));
}
}The constructor clamps the starting value. After construction, only charge and drain change percent. They bound the positive amount before arithmetic, preventing overflow even for Integer.MAX_VALUE. Nonpositive amounts are ignored. A client that writes b.percent = 150; gets a compile error. A method that only reads a field, such as getPercent, is an accessor, often called a getter. A method that changes the object's state is a mutator; a setter is the simplest kind.
Example: after Battery b = new Battery(64);, the call b.charge(50); adds only the 36 percentage points that fit, reaching 100. Then b.drain(30); leaves 70 percent.
Invariants: the rules a class promises to keep
A class invariant is a condition on an object's fields that holds when the constructor finishes and again after every public method returns. For Battery the invariant is
Encapsulation is what makes an invariant enforceable: if every change passes through methods that check the rule, no client can break it. With a public field, any client can store an invalid value, and finding that assignment may require searching every class that uses the object.
A mutator can enforce the rule in two common ways. It can reject an invalid request, leaving the field unchanged and often returning false, or it can clamp the result into range, as Battery does for positive amounts. Either works, provided the class documents which one it uses.
Question | Public field | Private field with methods |
|---|---|---|
Who can change the value? | Any client, by plain assignment | Only the class's own implementation |
Where is the rule checked? | Nowhere, or in every client | Inside the class |
A client requests a value of 150 | Direct assignment stores it silently | A method can reject or clamp it |
The storage format changes | Clients depending on the changed field need edits | Clients need no edits if public behaviour stays compatible |
A bad value appears | Search clients and the class | Inspect the class's state-changing code |
Changing the inside without breaking the outside
Suppose Battery should track energy in watt-hours for a 50 Wh pack. The internal representation can change while the public methods keep their signatures. This sketch shows the replacement field and accessor:
private double energyWh; // 0.0 to 50.0
public int getPercent() {
return (int) Math.round(energyWh / 50.0 * 100);
}At 32 Wh, this accessor reports 32/50×100=64 percent. That verifies only this state's reading. To preserve public behaviour, the constructor and mutators must also be rewritten: clamp starting percentages, ignore nonpositive amounts, and apply positive changes in percentage points with saturation at 0 and 100. Clients using the public interface can continue unchanged only when its documented behaviour is preserved. Clients that accessed a removed public percent field directly would need edits.
What to remember
- Encapsulation bundles data with the methods that act on it; clients use the methods, not the fields.
- Private fields plus validating mutators let a class guarantee its invariant after every public call.
- Mutators either reject or clamp invalid values; document which.
- Returning or storing a reference to a mutable private object leaks access; make a defensive copy.
- Hidden representation can change as long as public method signatures and documented behaviour stay compatible.
Example: Tracing a Thermostat That Guards Its Own Range
A smart thermostat must never hold a target temperature outside 10.0 °C to 30.0 °C. The class below keeps the target private, initializes it to a valid default, and validates requested changes in setTarget. This method returns false without changing the target whenever the requested value does not satisfy both bounds.
public class Thermostat {
private double targetC;
public Thermostat(double startC) {
targetC = 20.0;
setTarget(startC);
}
public boolean setTarget(double c) {
if (!(c >= 10.0 && c <= 30.0)) {
return false;
}
targetC = c;
return true;
}
public void adjust(double deltaC) {
setTarget(targetC + deltaC);
}
public double getTarget() {
return targetC;
}
}The condition also rejects Double.NaN, because comparisons of NaN with either bound return false.
A program runs these lines:
Thermostat t = new Thermostat(22.5);
t.adjust(4.0);
t.adjust(5.0);
boolean ok = t.setTarget(8.0);
t.adjust(-3.5);
System.out.println(t.getTarget() + " " + ok);a) Trace the program and state exactly what it prints.
The constructor first sets targetC to 20.0, then calls setTarget(22.5). Because 22.5 lies inside 10.0 to 30.0, the target becomes ________.
The call adjust(4.0) requests 22.5 + 4.0 = ________, which is in range, so it is stored.
The call adjust(5.0) requests 26.5 + 5.0 = ________. That is above 30.0, so setTarget returns false without assigning, and the target stays 26.5 °C. adjust ignores the returned value, so nothing else happens.
The call setTarget(8.0) is below 10.0, so it is rejected and ok holds ________.
The call adjust(-3.5) requests 26.5 − 3.5 = 23.0, which is in range and stored.
The program prints 23.0 false.
b) Suppose targetC were declared public instead. A client writes t.targetC = 35.0; and then calls t.adjust(-3.0);. What is the target afterwards, and why does this particular adjustment fail to restore a valid target?
The assignment goes straight to the field and skips setTarget, so no check runs and the target becomes 35.0 °C.
The call adjust(-3.0) requests 35.0 − 3.0 = ________. That is still above 30.0, so setTarget rejects it without changing the field.
Rejecting an invalid update preserves the existing state; it does not automatically repair a state that outside code has already made invalid. Recovery is still possible: a subsequent setTarget(20.0) would store 20.0, or adjust(-10.0) from 35.0 would store 25.0.
With targetC private, the client assignment t.targetC = 35.0; does not compile. After initialization, client requests must go through the validating methods, which prevent an invalid target from being stored in the first place.
After the specified assignment and adjust(-3.0) call, the target remains 35.0 °C.
c) The author later stores the target as a whole number of tenths of a degree. The constructor now sets targetTenths = 200 before calling setTarget(startC), and the other members become:
private int targetTenths;
public boolean setTarget(double c) {
if (!(c >= 10.0 && c <= 30.0)) {
return false;
}
targetTenths = (int) Math.round(c * 10);
return true;
}
public void adjust(double deltaC) {
setTarget(getTarget() + deltaC);
}
public double getTarget() {
return targetTenths / 10.0;
}Run the program from part a) unchanged. What integer does targetTenths hold at the end, and does the printed output change?
After the constructor, setTarget(22.5) stores the rounded value of 22.5 × 10, which is ________.
The call adjust(4.0) computes getTarget() = 225 / 10.0 = 22.5, adds 4.0 to get 26.5, and stores ________.
The call adjust(5.0) requests 31.5, which is rejected, so 265 remains. The call setTarget(8.0) is rejected, so ok is still false.
The call adjust(-3.5) requests 26.5 − 3.5 = 23.0 and stores 23.0 × 10 = 230.
The client program needs no edits because it accesses the target through public methods whose signatures are unchanged. Its output is unchanged for this trace. However, rounding means the implementations do not behave identically for every accepted input: after setTarget(22.54), the original returns 22.54, while the revised version returns 22.5. Hiding the representation lets its implementation change, but preserving general client behaviour also requires preserving the promised precision.
At the end of this program, targetTenths holds 230, and getTarget() returns 230 / 10.0 = 23.0. The program still prints 23.0 false.
A Rectangle class in a shared library declares public int width;, and dozens of client classes read and assign that field directly. The team wants to hide width behind methods and then enforce the invariant width > 0. Two rules govern the refactor. First, the whole program must compile after every step. Second, every step must deliver its full benefit at the moment it is made, so the width > 0 check may be added only once no client code can assign the field without going through the class. Put the steps in the order that satisfies both rules.
Loading ordering steps…
The Java class below keeps its balance private and ignores any deposit or withdrawal that would break its rules.
public class BankAccount {
private double balance;
public BankAccount(double opening) {
balance = opening;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}
public double getBalance() {
return balance;
}
}A program runs:
BankAccount acct = new BankAccount(120.00);
acct.deposit(-30.00);
acct.withdraw(45.50);
acct.withdraw(80.00);
acct.deposit(25.25);
acct.withdraw(10.00);
System.out.println(acct.getBalance());What balance does the program print, in dollars to two decimal places?