How to use getters and setters
Make fields private
Private fields can be accessed directly only inside their class.
class Account {
private double balance;
}
Add a getter
A getter exposes a value without allowing callers to assign the field directly.
public double getBalance() {
return balance;
}
Validate in a setter
A setter can reject values that would make the object invalid.
public void setBalance(double balance) {
if (balance < 0) {
throw new IllegalArgumentException("balance cannot be negative");
}
this.balance = balance;
}
Expose only what is needed
Not every field needs both methods. Omit a setter for values that should not change freely, and prefer behavior methods when they express the rule better.