Tsallaka zuwa abun ciki
Justice Tech School

Encapsulation

Make fields private and expose getters and setters with checks.

Example
public class Main {
  static class Account {
    private int balance;
    void deposit(int n) { if (n > 0) balance += n; }
    int getBalance() { return balance; }
  }
  public static void main(String[] args) {
    Account a = new Account();
    a.deposit(50);
    a.deposit(-5);
    System.out.println(a.getBalance());
  }
}

Result

50

Exercise

Hide a field.

 int balance;

Quiz Test

Why private fields?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.