Java encapsulation



In object-oriented programming methods, encapsulation (English: Encapsulation) refers to a method of partially packaging and hiding the implementation details of an abstract functional interface.

Encapsulation can be thought of as a protective barrier that prevents the code and data of the class from being randomly accessed by code defined by the external class.

To access the code and data of this class, you must pass strict interface control.

The main function of encapsulation is that we can modify our own implementation code without modifying the program fragments that call our code.

Proper encapsulation can make the program code easier to understand and maintain, and also enhance the security of the program code.

Example

Let us look at an example of a java encapsulation class:

/* 文件名: 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 public method in the above example is the entrance for external classes to access member variables of this class.

Normally, these methods are called getter and setter methods.

Therefore, any class that wants to access private member variables in the class must go through these getter and setter methods.

The following example illustrates how the variables of the EncapTest class are accessed:

/* F文件名 : RunEncap.java */
public class RunEncap{

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

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

The above code is compiled and run and the results are as follows:

Name : James Age : 20