codegurukool.com · Free coding tutorials & online compiler

Home › Java Tutorial › Java encapsulation

Java encapsulation

Hide data behind methods.

Mark fields private so other classes cannot change them directly, then offer public getters and setters. The class can then check values before accepting them. The access modifiers are public, protected, default (none) and private.

Example code

class Account {
  private double balance;

  public void deposit(double amount) {
    if (amount > 0) {
      balance += amount;
    }
  }

  public double getBalance() {
    return balance;
  }
}

public class Main {
  public static void main(String[] args) {
    Account a = new Account();
    a.deposit(50);
    a.deposit(-5);
    System.out.println(a.getBalance());
  }
}

Run this code in the online editor

← Java static membersJava inheritance →