private (Java)
private is an access modifier that restricts a field or method so it can only be used inside its own class. It is the foundation of encapsulation, hiding internal details from the rest of the program.
Java
By marking fields private and exposing them only through public methods (getters and setters), a class controls how its data is read and changed. This protects the object from being put into an invalid state.
Code in other classes that tries to access a private member directly will fail to compile.
Examples
Java
public class Account {
private int balance = 0;
public void deposit(int amount) {
if (amount > 0) balance += amount;
}
public int getBalance() {
return balance;
}
public static void main(String[] args) {
Account a = new Account();
a.deposit(50);
System.out.println(a.getBalance());
}
}Output:
50