๐Ÿ” 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;
    }
}