Encapsulation : It is a process by which wrapping code and data into a single unit.
Example : A java bean is a best example of heighly encapsulated class where any instance variable declared as private and these private variable can access through public method.
package com.pky.com;
public class Employee{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name=name
}
}
//save as EmpTest.java
package com.pky.com;
class EmpTest{
public static void main(String[] args){
Employee e=new Employee();
e.setName("Pradeep Yadav");
System.out.println(s.getName());
}
}
Output :
Pradeep Yadav
Advantage of Encapsulation :
Example : A java bean is a best example of heighly encapsulated class where any instance variable declared as private and these private variable can access through public method.
package com.pky.com;
public class Employee{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name=name
}
}
//save as EmpTest.java
package com.pky.com;
class EmpTest{
public static void main(String[] args){
Employee e=new Employee();
e.setName("Pradeep Yadav");
System.out.println(s.getName());
}
}
Output :
Pradeep Yadav
Advantage of Encapsulation :
* you can make the class read-only or write-only.
* you can control over the data