Wrapper of data member (variables) and methods (method) in a single unit is called Encapsulation.
// A simple example of encapsulation in Java
public class Person {
// Private variables to encapsulate data
private String name;
private int age;
// Public constructor to initialize the object
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Public getter method to access the private variable 'name'
public String getName() {
return name;
}
// Public setter method to modify the private variable 'name'
public void setName(String name) {
this.name = name;
}
// Public getter method to access the private variable 'age'
public int getAge() {
return age;
}
// Public setter method to modify the private variable 'age'
public void setAge(int age) {
this.age = age;
}
}
Encapsulation in Java is a fundamental concept of object-oriented programming that involves wrapping data (variables) and code (methods) together as a single unit. In the example above, the Person
class encapsulates the name
and age
properties. These properties are declared as private, meaning they cannot be accessed directly from outside the class. Instead, public getter and setter methods are provided to access and modify the private variables. This ensures that the internal representation of the object is hidden from outside interference and misuse, promoting modularity and maintainability of the code.