In the object-oriented design, the most critical problem is that "it will be separated from what will not be changed ".
Sometimes, in order not to allow the client programmers to modify things they should not modify, or to prevent the client program from having problems after modifying the Code, some access control operators must be set, to limit the access range.
There are four range controllers in Java: private, package (default range), protected, and public,
The permission ranges from small to large.
Method and attribute Access Control
The Private access scope is accessible only in this class.
The access scope of the Package is accessible to all classes in the package.
The access scope of Protected is a subclass of this class and can be accessed by classes in the same package as it.
Public can be accessed anywhere
Class Access Control
Class access permissions can only be package (default) and public
To prevent others from accessing this class at will, you can set the class constructor to private, so that only you can create this object.
You can use a static (static) method to create an object.
Instance:
Public class Sample {
Private Sample (){
System. out. println ("create a Sample ");
}
Public static Sample get Sample (){
Return new Sample ();
}
}
Alternatively, you can create a private static object and return the reference of this object through a public static method. In this way, you can implement the singleton (singleton) mode, only one object is created.
Instance:
Public class Sample {
Private static Sample s1 = new Sample ();
Public static Sample getSample (){
Return s1;
}}