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

  1. Private variables – Restrict access from outside the class.

  2. Public getter and setter methods – Provide controlled access to variables.

  3. Enhances security and maintainability.

  4. Helps in flexible implementation and code modularity.


2. Syntax of Encapsulation


 


3. Example: Encapsulation in Java


 

📌 Output:

Name: Alice
Age: 25

Direct access to name and age is not allowed because they are private. Access is only through getter and setter methods.


4. Advantages of Encapsulation

  1. Data Hiding – Prevents unauthorized access.

  2. Improved Security – Sensitive data cannot be modified directly.

  3. Code Flexibility – You can change the internal implementation without affecting outside code.

  4. Validation – Can validate inputs in setter methods.

  5. 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

You may also like...