Encapsulation is a core principle of Object-Oriented Programming in Java. It means binding data (variables) and methods together inside a class and controlling access to that data using access modifiers.
In Java, encapsulation is implemented by:
// Encapsulated class with private data and public methods
class Student {
private int age;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}
class Main {
public static void main(String[] args) {
Student s = new Student();
s.setAge(20);
System.out.println(s.getAge());
}
20
The age variable cannot be accessed directly. It is safely modified and read using setter and getter methods.
This demo simulates an encapsulated BankAccount class. The balance variable is private. You cannot change it directly; you must use the public methods which contain validation logic.
BankAccount class with private balancedeposit() and withdraw() methods