Encapsulation means wrapping data and methods into a single unit and restricting direct access to data using access modifiers.
Key benefits: It protects internal state from invalid changes, decouples code and makes systems easier to maintain.
Ex: A Car's Driving Controls
Private Data: The engine, fuel injection and transmission gears are enclosed under the hood.
Public Methods: As a driver, you only use public controls - the steering wheel, accelerator, and brake pedals which safely manage the engine's internal state without letting you accidentally break the mechanics.
class Student {
private int age;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}