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