Encapsulation and validation
Encapsulation is the rule that an object controls its own state. A field is private, the class offers methods that read and change it, and every change goes through a check. The code outside the class cannot put it into a state the class does not allow.
private
A private field is visible inside its class and nowhere else, not even in a subclass. The compiler refuses account.balance from another class, which is the point: the only way to change the balance is a method that knows the rules. Package-private, the default, is visible to the classes of the same package, and protected adds the subclasses; the inheritance lesson covers the last two.
A setter that refuses a value
The bank below checks both operations. A deposit must be positive, and a withdrawal must not exceed the balance; when a check fails, the method throws IllegalArgumentException with a message that names the value and the rule.
The file Bank.java:
public class Bank {
private int balance;
Bank(int balance) {
this.balance = balance;
}
void deposit(int amount) {
if (amount <= 0) {
throw new IllegalArgumentException("amount must be positive: " + amount);
}
balance += amount;
}
void withdraw(int amount) {
if (amount > balance) {
throw new IllegalArgumentException("insufficient funds: " + amount + " > " + balance);
}
balance -= amount;
}
int getBalance() {
return balance;
}
public static void main(String[] args) {
Bank bank = new Bank(100);
bank.deposit(50);
System.out.println("balance: " + bank.getBalance());
try {
bank.withdraw(500);
} catch (IllegalArgumentException error) {
System.out.println("refused: " + error.getMessage());
}
try {
bank.deposit(-5);
} catch (IllegalArgumentException error) {
System.out.println("refused: " + error.getMessage());
}
System.out.println("balance: " + bank.getBalance());
}
}
javac -Xlint:all Bank.java
java Bank
balance: 150
refused: insufficient funds: 500 > 150
refused: amount must be positive: -5
balance: 150
The balance is 150 after the deposit and is still 150 after the two refused operations. A method that throws does not leave a half-finished change behind: the check runs before the assignment, so the field never holds an invalid value.
The exception it throws
IllegalArgumentException is the standard unchecked exception for a value that is not allowed. It extends RuntimeException, so a method may throw it without declaring it, and a caller that does not catch it sees the message and a stack trace.
The choice between a boolean return and an exception is a design decision: false for an expected outcome the caller will handle, an exception for a programming error or a broken rule. A bank that refuses a withdrawal is an expected outcome; a deposit of a negative number is a mistake.
A read-only view
A private array field is not enough on its own: a getter that returns the array gives the caller a reference and the caller can change every element. The fix is a copy, a defensive copy in and out.
import java.util.Arrays;
public class ReadOnly {
private final int[] values;
ReadOnly(int[] values) {
this.values = values.clone();
}
int[] values() {
return values.clone();
}
public static void main(String[] args) {
ReadOnly readOnly = new ReadOnly(new int[] {1, 2, 3});
int[] copy = readOnly.values();
copy[0] = 99;
System.out.println(Arrays.toString(readOnly.values()));
}
}
javac -Xlint:all ReadOnly.java
java ReadOnly
[1, 2, 3]
The constructor clones the argument, so the caller cannot change the field through the array it passed. The getter clones the field, so the caller cannot change it through the array it received. Both copies are the same idea, and a class that skips either is not encapsulated even when the field is private.
Exercises
- Add a method transferTo(Bank other, int amount) that withdraws and deposits, and check that it leaves both balances right.
- Make the constructor of Bank.java refuse a negative opening balance and print the message.
- Remove one of the two clones in ReadOnly.java and observe which change the caller can make.
- Change a refusal in Bank.java to a boolean return and decide which version a caller would prefer.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
privateon a field prevent?Answer
Access from outside the class
A private member is visible only inside its own class, which is what keeps the state under the class control.
-
Which exception fits a method argument that breaks a rule?
Answer
IllegalArgumentException
It is the standard unchecked exception for an argument the method cannot accept.
-
Why does a getter return
values.clone()instead ofvalues?Answer
The caller cannot change the field through the returned array
Returning the field itself hands out a reference, and the caller could write every element.
-
What does this program print?
public class Q1 { public static void main(String[] args) { Acc acc = new Acc(); acc.deposit(10); acc.deposit(5); System.out.println(acc.balance()); } } class Acc { private int balance; void deposit(int amount) { if (amount > 0) { balance += amount; } } int balance() { return balance; } }Answer
15
Both deposits are positive, so both are added and the getter returns 15.
-
What does this program print?
public class Q2 { public static void main(String[] args) { Acc acc = new Acc(); acc.deposit(-10); System.out.println(acc.balance()); } } class Acc { private int balance; void deposit(int amount) { if (amount > 0) { balance += amount; } } int balance() { return balance; } }Answer
0
The setter ignores the negative value, so the field keeps its initial 0.
-
What does this program print?
public class Q3 { public static void main(String[] args) { try { withdraw(5); } catch (IllegalArgumentException error) { System.out.println(error.getMessage()); } } static void withdraw(int amount) { throw new IllegalArgumentException("too much: " + amount); } }Answer
too much: 5
The message is stored in the exception and printed by the catch.
-
What does this program print?
public class Q4 { public static void main(String[] args) { int[] inner = {1, 2}; int[] copy = inner.clone(); copy[0] = 9; System.out.println(inner[0]); } }Answer
1
clone creates a separate array, so the write to the copy is not visible in the original.
-
What is the first line of the compiler output for this program?
public class Q5 { public static void main(String[] args) { Acc acc = new Acc(); System.out.println(acc.balance); } } class Acc { private int balance; }Answer
error: balance has private access in Acc
A private field is not visible from main, and javac names the field and the class.
-
When is throwing an exception better than returning false?
Answer
When the caller broke a rule and cannot continue as if nothing happened
A false return suits an expected outcome; a broken rule or a programming error is the exception case.
-
What does a private field plus a getter and a setter give a class?
Answer
One place where the field can be read and one where it can change
All access goes through the methods, so a check or a copy can be added in one place.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev