Encapsulation is the concept of bundling the data (variables) and methods (functions) that operate on the data into a single unit or class. It is a way to restrict access to certain components and ensure that the object’s internal state cannot be directly accessed or modified from outside the class.
The idea behind encapsulation is to hide the internal state of an object and only expose a controlled interface for interacting with it. This is done through access modifiers like private
, protected
, and public
.
Why is Encapsulation Important
- Data Protection: It ensures that the internal data is protected and cannot be modified directly, reducing the risk of unauthorized access or changes.
- Code Maintenance: You can modify the internal implementation of the class without affecting the users of the class (as long as the public methods remain consistent).
- Validation: You can add validation and logic in setter methods to ensure that the object’s state remains consistent and valid.
How to Implement Encapsulation
- Private Fields: Make the fields (variables) of the class
private
so they cannot be accessed directly from outside the class. - Public Methods (getters and setters): Provide public getter and setter methods to access and update the value of the private fields. This allows you to control how the data is modified.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class Person { // Private fields private String name; private int age; // Getter method for name public String getName() { return name; } // Setter method for name public void setName(String name) { this.name = name; } // Getter method for age public int getAge() { return age; } // Setter method for age public void setAge(int age) { if (age > 0) { // Adding validation this.age = age; } else { System.out.println("Age cannot be negative!"); } } } |
- The
name
andage
fields are private, so they cannot be accessed directly from outside thePerson
class. - The
getName()
andgetAge()
methods are public and allow reading the private fields. - The
setName()
andsetAge()
methods are public, but they provide controlled access to modify the fields. In the case ofsetAge()
, it even has a validation to ensure that the age cannot be set to a negative number.