Encapsulation is one of the four fundamental concepts in object-oriented programming (OOP), along with inheritance, polymorphism, and abstraction. Encapsulation is the technique of bundling the data (attributes) and the methods (functions) that operate on the data into a single unit called a class. It restricts direct access to some of an object's components, which is a means of preventing accidental interference and misuse of the data.
To achieve encapsulation in Java, follow these steps:
class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = 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) { // Validating age
this.age = age;
}
}
}
public class TestEncapsulation {
public static void main(String[] args) {
// Creating an instance of the Person class
Person person = new Person("John", 25);
// Accessing private fields through getter methods
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
// Modifying private fields through setter methods
person.setName("Jane");
person.setAge(30);
// Accessing modified fields through getter methods
System.out.println("Updated Name: " + person.getName());
System.out.println("Updated Age: " + person.getAge());
}
}
Name: John
Age: 25
Updated Name: Jane
Updated Age: 30
Encapsulation is a powerful concept in OOP that promotes data hiding, access control, and modularity. By bundling data and methods into a single unit (a class) and restricting direct access to the data, encapsulation helps improve the maintainability, security, reusability, and flexibility of your code. Understanding and applying encapsulation effectively is essential for writing robust and maintainable Java applications.