Access Modifiers and Encapsulation
public means visible everywhere, private only inside the class, protected in the package and subclasses, and no modifier means package only. Encapsulation keeps fields private and exposes them through getters and setters so the class can validate changes.
Example
class Account {
private double balance;
public double getBalance() { return balance; }
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
}
public class Main {
public static void main(String[] args) {
Account a = new Account();
a.deposit(500);
a.deposit(-20);
System.out.println(a.getBalance());
}
}Result
500.0
Exercise
Hide the field from other classes.
double balance;Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.