Pages

Encapsulation

Encapsulation
Definition

Encapsulation is the process of wrapping up of data and methods into a single unit is knwon as Encapsulation. The variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class.

Advantages 1. We can Easy to Test the Encapsulation Code.
2. We can Hide the Encapsulation Data.
3. We can Increate the Flexibility of Encapsulation Data.
4. We can Easy to change the new requirement.
Encapsulation Example package com.jaladhi.jst;
public class Student {
      private String no;
      private String name;
      private String age;
      public void setNo(String no) {
            no = no;
      }
      public int getNo() {
            return no;
      }
      public void setName(String name) {
            name = name;
      }
      public String getName() {
            return name;
      }
      public void setAge(String age) {
            age = age;
      }
      public String getAge() {
            return age;
      }
}
package com.jaladhi.jst;
public class StudentTest {
      public static void main (String[] args) {
            Student student = new Student();
            student.setNo("1000");
            student.setName("David Kenten");
            student.setAge("30");
            System.out.println("Student Number : " + student.getNo());
            System.out.println("Student Name : " + student.getName());
            System.out.println("Student Age : " + student.getAge());
      }
}
Output :
Student Number : 1000
Student Name : David Kenten
Student Age : 30


package com.jaladhi.jst;
public class Person {
      private String name;
      private String city;
      private String state;
      public void setName(String name) {
            no = no;
      }
      public int getName() {
            return name;
      }
      public void setCity(String city) {
            city = city;
      }
      public String getCity() {
            return city;
      }
      public void setState(String state) {
            state = state;
      }
      public int getState() {
            return state;
      }
}
package com.jaladhi.jst;
public class PersonTest {
      public static void main (String[] args) {
            Person person = new Person();
            person.setName("David Kenten");
            person.setCity("New York City");
            person.setState("New York State");
            System.out.println("Person Name : " + person.getName());
            System.out.println("Person City : " + person.getCity());
            System.out.println("Person State : " + person.getState());
      }
}
Output :
Student Number : David Kenten
Student Name : New York City
Student Age : New York State