Encapsulation
What Is Encapsulation?
Encapsulation
An OOP principle where data (attributes) and the methods that operate on it are bundled together within a class, while restricting direct access to the data to protect it from unintended interference.
In other words, encapsulation restricts direct access to some of an object's components, ensuring that data is accessed and modified only through well-defined interfaces.
AnalogyEncapsulation is often described as a protective wall that shields an object's internal state from external interference.
How Encapsulation Works
Encapsulation relies mainly on combining private attributes with public methods to control and protect how data is accessed and changed.
It is possible via access modifiers that define who can see or use a class, method, or variable:
- public: accessible from anywhere in the program.
- private: accessible only within the same class (most common for attributes).
- protected: accessible within the same class, subclasses, and the same package.
- default (package-private): if no modifier is given, it is accessible only within the same package.
Such a structure ensures that data can only be modified in controlled ways, preventing vulnerabilities and unintended side effects.
Analogy- Think of encapsulation like a car's dashboard.
- You can control the car (accelerate, brake, steer), but cannot gain access to the car's fuel tank and engine.
Common encapsulation methods are getters and setters:
Getters
Methods used to retrieve the value of private attributes.
Setters
Methods used to update the value of private attributes (in a controlled way).
They support encapsulation by allowing access without exposing the variable directly.
public class Student {
private String name; // private attribute that cannot be modified directly
public String getName() { // getter
return this.name;
}
public void setName(String name) { // setter
// here you can include additional validation/actions
this.name = name;
}
public static void main(String[] args) {
Student s = new Student();
// using setter
s.setName("Alice");
// using getter
System.out.println("Student name: " + s.getName());
}
}
- While encapsulation often involves making attributes private, its primary goal is to create a clear and controlled interface for interacting with an object.
- All methods that work with the class are coded within the class.
- Not every attribute needs a getter or setter.
- Only expose methods that are essential for the class's intended use.
- A common mistake is to make all attributes public for convenience.
- This undermines the benefits of encapsulation and can lead to fragile code.
- When designing a class, always start by identifying which attributes and methods should be private and which should be public.
- This helps ensure a clean and robust design.