Encapsulation is another important principle of object-oriented programming (OOP) in Java. It is the process of bundling data (attributes) and methods (behaviors) that operate on the data within a single unit, called a class. The main idea behind encapsulation is to hide the internal details of an object and provide a well-defined interface (public methods) to interact with the object.
In Java, encapsulation is achieved by using access modifiers (public, private, protected, and default) to control the visibility of class members (variables and methods). Here’s how encapsulation works:
Private Access Modifier: By declaring a variable or method as private, you restrict access to it from outside the class. Only methods within the same class can access private members. This ensures that the internal state of an object is not directly accessible from other classes.
public class Person {
private String name;
private int age;
// Public getter and setter methods for private variables
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public int getAge() {
return age;
}
public void setAge(int newAge) {
if (newAge >= 0) {
age = newAge;
}
}
}
Public Access Modifier: Methods that are meant to be accessed from outside the class are declared as public. These methods provide the interface through which external code can interact with the object’s state and behavior.
Protected Access Modifier: Protected members can be accessed within the same package or by subclasses, even if they are in different packages. This allows for controlled access to specific members while still maintaining encapsulation.
Default (Package-private) Access Modifier: If no access modifier is specified, the member has default (package-private) access. Members with default access can be accessed only by classes within the same package.
By encapsulating the data and methods within a class and providing well-defined access points (e.g., public methods), you create a clear separation between the internal implementation and the external usage of an object. This helps in maintaining data integrity, reducing dependencies between different parts of the code, and making it easier to modify the internal implementation without affecting the overall functionality of the program. Encapsulation is a crucial concept in OOP as it supports information hiding and improves the robustness and maintainability of your Java code.