Effective access such as Java

Source: Internet
Author: User

The smaller the accessibility of the class, the better, that is enough, between different packages and modules, only the API interface is reserved for sufficient functionality, and the details of all the other features are encapsulated inside the package, so that the maintainability and extensibility of the code can be greatly improved. So, what are the access controls in Java?

Public: This is the equivalent of "my door often open", anyone can enter, which is certainly quite unsafe.

Second, the default access rights: This access is equivalent to only within the same package, the class can be called each other, and the method must be called protected level and above.

Third, protected: this is applicable to inheritance, regardless of the subclass in which package, can be accessed.

Iv. private: This is tantamount to declaring personal property and not infringing it.

There are other rules, such as the way that the subclass inherits the access permission must not be less than the parent class, so that the parent class can invoke the method inherited by the subclass.

Also, for some thread-safe classes, in addition to the "synchronous" mechanism, you can use the final class to declare all the properties in the class as final so that the properties of the same instance will not be changed. Examples are as follows:

 package   demo;  public  final  class   Finaltest { final  int   A;  public  finaltest (int   a) { this . A = A;  public  int   Geta () { return   A; }}

In this way, the A attribute in Finaltest is not changed in different threads. But immutable classes also have some drawbacks, if you want to change the properties in the Finaltest instance, then only re-create an instance of Finaltest, which has a certain effect on performance.

In short, in class design, only open outward should open the interface, encapsulating the details of the implementation of the class inside, this is easy to say, but in practice, it takes a lot of experience.

Effective access such as Java

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.