Java hide implementation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.