Java Encapsulation
🔹 Java Encapsulation
Encapsulation is an OOP concept that wraps data (variables) and methods together in a class and restricts direct access to some of the object’s components.
It is also known as data hiding.
✅ 1. Key Features of Encapsulation
-
Private variables – Restrict access from outside the class.
-
Public getter and setter methods – Provide controlled access to variables.
-
Enhances security and maintainability.
-
Helps in flexible implementation and code modularity.
✅ 2. Syntax of Encapsulation
✅ 3. Example: Encapsulation in Java
📌 Output:
Direct access to
nameandageis not allowed because they are private. Access is only through getter and setter methods.
✅ 4. Advantages of Encapsulation
-
Data Hiding – Prevents unauthorized access.
-
Improved Security – Sensitive data cannot be modified directly.
-
Code Flexibility – You can change the internal implementation without affecting outside code.
-
Validation – Can validate inputs in setter methods.
-
Better Maintainability – Keeps code modular and organized.
✅ 5. Key Points
| Feature | Description |
|---|---|
| Private variables | Cannot be accessed directly from outside class |
| Public getter/setter | Used to read/write private variables |
| Validation | Can restrict invalid data using setters |
| OOP Principle | Encapsulation is part of Abstraction and Data Hiding |
