Encapsulation

Encapsulation

  1. Hiding your data and binding your data in single unit that is called encapsulation.
  2. Data hiding is called encapsulation.
  3. It is a major components of object oriented programming.
  4. Encapsulation class is a reusable software.
  5. In Web Architecture it is also called Java Beans and POJO class (Plain Old Java Object).
  6. It is also used to exchange Information from one class to another class.
  7. It is also called Model class or DTO (Data Transfer Object) in MVC design pattern.

Encapsulation Rule :

  1. All data member should be private.
  2. for each data member we need to create two public type of method :
  3. setter
  4. getter
  5. Constructor should be default.

class Student {
            private String name;
            private int roll;
        
            public String getName() {
                return name;
            }
        
            public void setName(String name) {
                this.name = name;
            }
        
            public int getRoll() {
                return roll;
            }
        
            public void setRoll(int roll) {
                this.roll = roll;
            }
        }
        
        class College {
        
            public void send(Student student) {
                new Institute().receive(student);
            }
        
        }
        
        class Institute {
            public void receive(Student student) {
                System.out.println(student.getName());
                System.out.println(student.getRoll());
            }
        }
        
        public class Test {
            public static void main(String[] args) {
                Student student = new Student();
                student.setName("sonu singh");
                student.setRoll(1);
        
                College college = new College();
                college.send(student);
                
            }
        }
        

No comments: