Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java encapsulation


May 10, 2021 Java


Table of contents


Java encapsulation


In object-oriented program design, encapsulation refers to a method of wrapping and hiding the practical details of abstract letter interfaces.

Encapsulation can be considered a protective barrier to prevent code and data of the class from being accessed randomly by code defined by external classes.

To access the code and data of this class, it must be controlled through a strict interface.

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

Proper encapsulation makes the code easier to understand and maintain, and also enhances the security of the code.

Instance

Let's 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 instance is an entry point for an external class to access a member variable of that class.

Typically, these methods are called getter and setter methods.

Therefore, any class that wants to access private member variables in a class passes through these getter and setter methods.

Illustrate how variables of the EncapTest class are accessed by following examples:

/* 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 compiles and runs as follows:

Name : James Age : 20