Packaging and its necessity

  1. Encapsulation hides internal details. Exposing only interface encapsulation has the advantage of hiding implementation details, which is convenient for users to keep the interface unchanged. Declare the following classes:
public class Person{
    public Integer age;
    public Integer id;
    public String name;
}
Copy the code

This class is called in many other places, but it becomes inconvenient to later process variables in it, such as formatting ids. Make the following changes:

public class Person{ private Integer age; private Integer id; private String name; // Change to private so that it cannot be accessed directly from outside the class. public voidsetId(Int Id){// Expose the interface to processif(id){
            ...
        } else{... }}}Copy the code

Access control character

Control characters

  1. Public Any place where the corresponding entity is generated can be accessed through the dot operator.
  2. Ptotected is accessible only to subclasses (extends) and classes that are part of the same package.
  3. Package Private Package-level private. Only those in the same package can be accessed. The default is package-level private without any access control characters.
  4. Private is available only to the current class.

Packages do not contain nested relationships.

JavaBean conventions (widely used)

  1. Getter A method that gets a property
  2. Setter setter setter setter setter setter setter setter setter setter setter setter setter setter setter setter setter setter When using Fastjson, the set + property starts with a capital letter and finds that the values he reads are obtained through the getter.

Class access control character

  1. Package level private
class Cat{}
Copy the code

That is, you can access the same package but cannot access the same package. You can ask questions in public anywhere. Classes of the same package can be accessed. 4. Private can only be accessed in the same class.