After learning Java for two years, I suddenly found myself confused about the basic concepts of public, friendly, private, and protected, so I opened thinking in Java se...
Summary:
Public:The data member and member Methods declared as public can be used by all clients.ProgramStaff use.
Friendly:For all classes in the same package, if the two classes are placed in the same directory but the package is not declared, Java considers the two classes to belong to the same package, that is, the friendly data member and member methods are available.
PRIVATE:It cannot be seen by the outside world and can only be called by the member methods in the class. To implement the Java "Hide Implementation Details" principle, data members should be declared as private. If the constructor is declared as private, the client programmer cannot directly generate the object of this class, and can only generate the object of this class through the static method provided by the class. Is this the "factory model" in "Design Model?
Example:
Public Class {
Private (){}
Public static makea (){
Return new ();
}
Public static void main (string [] ARGs ){
//!~ A A = new A (); error, can't use new to create an object
A A = A. makea ();
}
}
Protected:A member declared as friendly can only be called by the class in the same package. If you want a class to inherit the class in another package, you can call the data member and member methods of the class, you need to declare the data member and member method as protected. For classes in the same package, protected serves as friendly.