Hide an object's data behind methods so it can never be put into a bad state, like a negative deposit.
Java · beginner · 7 min · 14 steps · free
class BankAccount {
private double balance;
double getBalance() {
return balance;
}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
public class EncapsulationDemo {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(50);
acc.deposit(-20);
System.out.println(acc.getBalance());
}
}BankAccount constructor to set up the new object. The program starts in main. args holds its command-line arguments (none here).BankAccount() has finished, so its variables are gone.acc is created on the stack and points to a new BankAccount on the heap: {balance: 0}.deposit(), with amount = 50. It gets its own variables on the stack.balance in the BankAccount that acc points to changes from 0 to 50.deposit() has finished, so its variables are gone.deposit(), with amount = -20. It gets its own variables on the stack.deposit() has finished, so its variables are gone.getBalance(). It gets its own variables on the stack.getBalance() has finished, so its variables are gone.50.0.Answer: private. private limits access to the class.
Answer: The class keeps control of its data. You can add rules later without changing callers.
← static: Shared by the Whole Class · Inheritance and super →