Dezign Patterns
Encapsulation
📦 Definition: Wrapping data (variables) and code (methods) into a single unit (class).
🎯 Intent : Protect the object's state from direct access.
- Before OOPS, most of the code was procedural — meaning functions and data were separate. This made codebases messy.
- Any function could change any data at any time.
- No control over how values were set or used - No consistency or safety
In java, we make fields private and accessing/modifying fields using public getters/setters
private int age; // private = encapsulated
public void setAge(int age) {
if (age > 0) { // Public setter for age (with validation)
this.age = age;
}
}
public double getSalary() {
return Math.round(salary * 100.0) / 100.0; // Return formatted or adjusted value
}
External code can't directly access or mess with private fields. (e.g., emp.age = -1 is invalid.)