One of the characteristics of the four java package -------

 For packaging, the package it is an object of their properties and methods, it does not depend on other objects that can complete its operation.

       Use the package has three advantages:

          1, good encapsulation can be reduced coupling.

           2, the internal structure of the class can be modified freely.

          3 allows for more precise control of the members.

          4, hidden information, the implementation details.

 Package literally be understood that the meaning of the packaging, information hiding point is professional, is the use of abstract data types and data based on the operation data packaged together, so that it constitutes an integral part of the independent entity, the data is protected abstract data types internal, hidden as much as possible the details of the interior, retaining only some of the external interface to make contact with the outside. Other objects of the system to communicate and interact only with the encapsulated object by wrapping data out operation has been authorized. That is the user need not know the details of the interior of the object (of course, do not know), but you can access the object through the interface provided by the external objects.
 

The following is an example of using the package:

/* 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;
   }
}

Public access from outside the class is the class field into the inlet. Typically, these methods are defined as getters and setters. So you want to access the class variables within any other class to use getters and setters.

EncapTest class variables can be accessed as follows:

/* File name : 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());
    }
}
//这将产生下述结果:
Name : James Age : 20
  • Class field may be set to read-only or write-only.
  • It can completely control what class field stored inside.
  • Users do not know the type of class is how to store the data. Class can change the data type field of the class before users need to change any code.

Guess you like

Origin blog.csdn.net/qq_45097560/article/details/91453091