What is Encapsulation in Java?
Encapsulation is one of the four fundamental object-oriented programming (OOP) concepts in Java. It is the process of wrapping up data and methods into a single unit called a class. This allows us to protect the data from unauthorized access and make sure that the data is used in a consistent way.
In Java, encapsulation is achieved by using access modifiers. Access modifiers are keywords that control the accessibility of class members, such as variables and methods. There are three types of access modifiers in Java:
- public: This is the most accessible modifier. Any class can access public members.
- protected: This modifier is accessible to subclasses of the class in which it is declared.
- private: This modifier is the least accessible modifier. Only the class in which the variable or method is declared can access private members.
To encapsulate data in Java, we can declare the data members of a class as private and provide public getter and setter methods to access the data. For example:
public class Employee {
private String name;
private int age;
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;
}
}
In this example, the name
and age
variables are declared as private, so they can only be accessed by the methods of the Employee
class. The getName()
and setName()
methods are public, so they can be accessed by any class.
Comments
Post a Comment