Java Encapsulation
Encapsulation is one of the four fundamental concepts of Object-Oriented Programming (OOP) and is used to achieve data hiding and abstraction in Java. It refers to the mechanism of binding data and code that operates on the data within a single unit or object.
Encapsulation is implemented in Java by creating objects that contain data and methods that operate on that data. The data is defined as instance variables, and the methods that operate on the data are called member methods.
The instance variables are kept private, making them inaccessible from outside the object. Instead, access to the data is provided through public methods, which serve as an interface between the object and the code that uses the object.
Example:
public class Employee {
private int id;
private String name;
private int age;
private String designation;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
In the above example, the instance variables id
, name
, age
, and designation
are kept private and can only be accessed through the public methods getId()
, getName()
, getAge()
, getDesignation()
, setId()
, setName()
, setAge()
, and setDesignation()
.
This ensures that the data is kept safe and secure, as it can only be accessed and modified through a well-defined interface.
In conclusion, encapsulation provides a secure mechanism for data hiding and abstraction and helps to maintain the integrity of the data in an object. It is a key concept in OOP that enables objects to function as self-contained units.