( aim to restrict direct access )
Binding code and data together into a single unit are known as encapsulation. For example, a capsule, it is wrapped with different medicines.
- Binding of
data
and correspondingmethods
into a single unit is called "Encapsulation". - If any java class follows
data hiding
andabstraction
then such class is referred as "Encapsulation class"
class Person {
private String name; // Instance Variable
private int age; // Instance Variable
public String getName() {
return name; // Getters for Name
}
public void setName(String name) {
this.name = name; // Setters for Name
}
public int getAge() {
return age; // Getters for Age
}
public void setAge(int age) {
this.age = age; // Setters for Age
}
}
public class demo {
public static void main(String[] args) {
Person person = new Person(); // creating object person
person.setName("Rohit");
person.setAge(22);
System.out.println("Name:" + person.getName());
System.out.println("Age:" + person.getAge());
}
}
- If both local variable and instance variable have the same name inside the method then it would result in a name_class and jvm will always give preference for local variable. This approach is called the "Shadowing Problem".
Getters method are used to get the value from the instance variable of the class.
Syntax for getters method
- the method name should start with get
- it should be public
- return type should not be void
- it should not have any arguments
public String getName() {
return name; // Getters for Name
}
Setters method are used to set the value to the instance variables of the class.
Syntax for setters method
- the method name should start with set
- it should be public
- return type should be void
- it should have some arguments
public void setName(String name) {
this.name = name; // Setters for Name
}