Encapsulation is one of the fundamental principles of object-oriented programming. It refers to the bundling of data (fields) and methods that operate on the data into a single unit, typically a class. Encapsulation also involves restricting direct access to some of the object’s components, which is usually achieved through access modifiers and providing controlled access via getter and setter methods.
class Person {
// Private fields
private String name;
private int age;
// Public getter for name
public String getName() {
return name;
}
// Public setter for name
public void setName(String name) {
this.name = name;
}
// Public getter for age
public int getAge() {
return age;
}
// Public setter for age
public void setAge(int age) {
if (age > 0) {
this.age = age;
} else {
System.out.println("Please enter a valid age");
}
}
}
public class Main {
public static void main(String[] args) {
= new Person();
Person person .setName("John");
person.setAge(30);
person
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
Java provides several access modifiers to set access levels for classes, variables, methods, and constructors:
private
: The member is accessible only
within the class in which it is defined.default
(no modifier): The member is
accessible only within classes in the same package.protected
: The member is accessible
within its own package and by subclasses.public
: The member is accessible from
any other class.Encapsulation is a key concept in Java that promotes information hiding and helps maintain a clean and flexible structure of classes. By encapsulating fields and controlling access through methods, developers can ensure that the internal state of objects is protected and consistent, leading to more robust and maintainable code.