Definition-

Encapsulation is a concept of binding data and code together in single unit.

-In java, data means data members, and code means methods.

– In java, in encapsulation, data members are private and access methods (setters and getters) are public.

1- Creation of encapsulation class-


package ncapsulsn;

public class ExEncapsulated {

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;
}
}

2- Usege of encapsulation class-

package ncapsulsn;

public class UseEncapsulated {

public static void main(String[] args) {
ExEncapsulated e1=new ExEncapsulated();
e1.setName("xyz");
e1.setAge(5);
ExEncapsulated e2=new ExEncapsulated();
e2.setAge(17);
System.out.println(e2.getAge());
}
}

Advertisements