Encapsulation is one of the fundamental concepts of object-oriented programming (OOP) in Java. It is the technique of bundling the data (variables) and the methods (functions) that operate on the data into a single unit, called a class. Encapsulation is used to hide the internal state of an object from the outside world and only expose a controlled interface for interaction with the object.
Key Concepts of Encapsulation:
- Data Hiding:
- Encapsulation allows the internal representation of an object to be hidden from the outside. This is achieved by making the class variables private and providing public getter and setter methods to access and modify these variables.
- Controlled Access:
- By using getter and setter methods, you can control how the important data of an object is accessed and modified. This adds a layer of protection and helps in maintaining the integrity of the data.
- Modularity:
- Encapsulation helps in keeping the code modular. Each class is responsible for its own data and behavior, making it easier to manage and maintain the codebase.
public class Person {
// Private variables
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Public getter method for name
public String getName() {
return name;
}
// Public setter method for name
public void setName(String name) {
this.name = name;
}
// Public getter method for age
public int getAge() {
return age;
}
// Public setter method for age
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
// Method to display person’s details
public void displayInfo() {
System.out.println(“Name: ” + name);
System.out.println(“Age: ” + age);
}
}
public class Main {
public static void main(String[] args) {
// Creating an object of the Person class
Person person = new Person(“John”, 25);
// Accessing and modifying the data using getter and setter methods
person.setName(“Jane”);
person.setAge(30);
// Displaying the person’s details
person.displayInfo();
}
}
Leave a Reply