Encapsulation



Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.

  • Binding the data with its related functionalities known as encapsulation
  • Here data means variables and functionalities means methods.
  • So keeping the variable and related methods in one place.
  • That place is "class". class is the base for encapsulation.
  • Lets see example program on encapsulation, how the variables and methods defined in a class

/* File name : EncapTest.java */
public class EncapTest {
   private String name;
   private String idNum;
   private int age;

   public int getAge() {
      return age;
   }

   public String getName() {
      return name;
   }

   public String getIdNum() {
      return idNum;
   }

   public void setAge( int newAge) {
      age = newAge;
   }

   public void setName(String newName) {
      name = newName;
   }

   public void setIdNum( String newId) {
      idNum = newId;
   }
}

The variables of the EncapTest class can be accessed using the following program −



public class RunEncap {

   public static void main(String args[]) {
      EncapTest encap = new EncapTest();
      encap.setName("John");
      encap.setAge(20);
      encap.setIdNum("123");

      System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());
   }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.