Keep the data safe
If anyone can change a field directly, they can put nonsense in it, like a negative bank balance. Encapsulation means hiding the fields with private and only letting other code change them through methods that check the values first.
Think of it like this: A bank doesn't let you walk into the vault and take money. You go to the counter (a method), and the cashier checks that you have enough first.
class BankAccount {
private String owner;
private double balance;
BankAccount(String owner) {
this.owner = owner;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
}
return false;
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount("Asha");
acc.deposit(500);
System.out.println(acc.withdraw(800));
System.out.println(acc.withdraw(200));
System.out.println(acc.getBalance());
}
}Output
false true 300.0
Now nobody can write acc.balance = -1000:
class BankAccount {
private double balance;
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.balance = -1000;
}
}Output (the program does not compile)
Main.java:8: error: balance has private access in BankAccount
acc.balance = -1000;
^Access modifiers
| Keyword | Who can use it |
|---|---|
public | everyone |
private | only code inside the same class |
protected | the same package and child classes (see the Inheritance module) |
| (nothing) | code in the same package |
Tip: A good habit: make fields
private, and add agetX()method to read them and asetX()method (with checks) only if they really need to change.