public class Person {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
//parent class
public class Test {
public static void main(String[] args) {
Person p1 = new Person();
p1.setName("Sabbir");
System.out.println(p1.getName());
}
}
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Another way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield.
1-ENCAPSULATION: We can hide direct access to data by using
private key and we can access private data by using getter and
setter method.