Latest web development tutorials

Java Package

In object-oriented programming method, the package (English: Encapsulation) refers to a way to abstract the real function of the interface as part of the package details, hidden way.

Package can be thought of as a protective barrier against the class code and data are defined outside the class code for random access.

To access the class code and data must pass rigorous interface.

The main function of the package is that we can modify your implementation code, without modifying the code we call those the program fragment.

Appropriate packaging can make the code easier to understand and maintain, and enhance the security code.

Examples

Let's look at an example of java package 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 above example public methods of the outer class access the class member variable entrance.

Typically, these methods are called getter and setter methods.

Thus, any class to access class private member variable to go through these getter and setter methods.

Explanatory variables EncapTest class by the following examples of how to be 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 results are as follows:

Name : James Age : 20