๐ Encapsulation
Encapsulation is one of the four core principles of Object-Oriented Programming. It involves wrapping data and code that operates on the data into a single unit: the class.
๐งฉ Key Concepts
- Declaring variables as
private
to prevent direct access from outside. - Providing
public
methods (getters/setters) to read or modify private variables. - Helps enforce data protection, validation, and clean APIs.
๐ Why Use Encapsulation?
- Keeps internal implementation hidden
- Prevents external interference or misuse
- Allows safe and controlled access
- Promotes modularity and maintainability
๐งช Java Example
class Student {
private int age;
// Setter with validation
public void setAge(int a) {
if (a > 0) age = a;
}
// Getter
public int getAge() {
return age;
}
}