Encapsulation Example in java

In this tutorial, we will write an encapsulation program in java. Before that, you should have knowledge on the following topic in Java.


Encapsulation in Java using setter and getter

 class StudentInfo
 {
   private int id;
   private String stdName;
   private int stdAge;

   //Getter methods
   public int geStdiID()
   {
     return id;
   }

   public String getStdName()
   {
     return stdName;
   }

   public int getStdAge()
   {
     return stdAge;
   }

   // Setter methods
   public void geStdiID(int newId)
   {
     id = newId;
   }

   public void getStdName(String newName)
   {
     stdName = newName;
   }

   public void getStdAge(int newAge)
   {
     stdAge = newAge;
   }
 }

 public class EncapsTest
 {
   public static void main(String args[])
   {
     StudentInfo obj = new StudentInfo();

     obj.geStdiID(1101);
     obj.getStdName("Marshall");
     obj.getStdAge(20);

     System.out.println("Student Id: " + obj.geStdiID());
     System.out.println("Student Name: " + obj.getStdName());
     System.out.println("Student Age: " + obj.getStdAge());
   }
 }

Output:

Student Id: 1101
Student Name: Marshall
Student Age: 20