Encapsulation:
Encapsulation is a process of packaging variables and method into a single unit and protecting data by declaring them as private. Where private is hidden from the other classes and the can only be accessed through the method of their current class. This is known as data hiding.
Process:
Encapsulation is a process of packaging variables and method into a single unit and protecting data by declaring them as private. Where private is hidden from the other classes and the can only be accessed through the method of their current class. This is known as data hiding.
Process:
- Declare the variables as private.
- Provide public setter and getter method to modify and get the variables value.
- Provides data hiding.
- Reusability
- Code can be modified without breaking the code.
- Reduce complexity.
- public class PersonE {
- private String name;
- private String gender;
- private int age;
- public String getName() { //Getter method
- return name;
- }
- public void setName(String name) { //Setter method
- this.name = name;
- }
- public String getGender() {
- return gender;
- }
- public void setGender(String gender) {
- this.gender = gender;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
- // Main class
- public class EncapsulationDemo {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- PersonE p1=new PersonE();
- p1.setName("Sujan Hasan");
- p1.setGender("Male");
- p1.setAge(21);
- print(p1);
- System.out.println();
- PersonE p2=new PersonE();
- p2.setName("Shimul Hossain");
- p2.setGender("Male");
- p2.setAge(22);
- print(p2);
- System.out.println();
- PersonE p3=new PersonE();
- p3.setName("Shakil Sorker");
- p3.setGender("Male");
- p3.setAge(22);
- print(p3);
- System.out.println();
- }
- public static void print(PersonE obj) {
- System.out.println(obj.getName());
- System.out.println(obj.getGender());
- System.out.println(obj.getAge());
- }
- }
0 Comments:
Post a Comment