Encapsulation
Encapsulation in Java is an object-oriented programming concept that bundles data and the methods that operate on that data into a single unit, such as a class. It also helps control access to the object's internal state by restricting direct access and providing controlled ways to read or modify it.
- Usually uses private fields to restrict direct access.
- Provides controlled access through methods such as getters and setters when required.
- Allows validation and other rules to be applied before changing data.
How Encapsulation is Achieved in Java
Encapsulation is commonly implemented by:
- Declaring fields as private.
- Providing public or appropriately accessible methods to read or modify the fields.
- Adding validation inside methods when necessary.
- Keeping the internal implementation hidden from code outside the class.
Example: Encapsulation in Java
`class Student {
// Private variables private String name; private int age; // Setter method public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } // Getter methods public String getName() { return name; } public int getAge() { return age; } }`
`public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // Setting values s1.setName("Gowtham"); s1.setAge(21); // Getting values System.out.println(s1.getName()); System.out.println(s1.getAge()); } }`
Output:
Gowtham
21
Advantages of Encapsulation
- Protects an object's internal data from direct access.
- Allows validation before data is modified.
- Makes code easier to maintain and modify.
- Keeps related data and methods together in one class.
- Reduces dependency on the internal implementation of a class.
- Provides better control over how an object's state can be accessed or changed.
Limitations of Encapsulation
- Can increase the amount of code when many accessor methods are required.
- May add unnecessary complexity for very simple classes.
- Requires careful design to decide which data and operations should be exposed.
- Excessive use of getters and setters can expose more of a class's internal state than necessary.

