The most important factor in distinguishing a good module from a bad one is whether a module hides internal data and other details from other modules. A good module hides all the details, isolates the API from the implementation, and uses the API to communicate with each other. This is information hiding or encapsulation. Is one of the basic principles of software design.
(5) Information hiding is the greatest significance of it (couples) the modules that comprise a system. Modules can then be developed and tested independently. Improved reusability.
Many facilities in Java assist in information hiding, such as access control, which determines class, interface, and member accessibility.
The rule of thumb: ** Makes every class or member as inaccessible as possible. ** is the lowest level of access.
Top-level classes and interfaces
At Top level classes and interfaces, there are only two possible access levels:
- Package -priavte The member is accessible from any class in The package where it is declared
- public
Member (fields, methods, classes, and nested interfaces)
- Private — The member is accessible only from The top-level class where it is declared.
- Package-private — The member is accessible from any class in The package where it is declared. Demeaning known as default access, this is the access level you get if no access modifier is specified.
- Protected — The member is accessible from subclasses of The class where it is declared (subject to a few restrictions) [JLS, 6.6.2]) and from any class in the package where it is declared.
- Public — The member is accessible from anywhere.
-
Accessibility increases greatly when you change package-private to protected. Protected members should be used as little as possible.
-
The access level of a method overridden in a subclass cannot be lower than that of the parent. In particular, for interfaces, all methods in interfaces implicitly have a public access level; So if a class implements an interface, all methods in that interface must also be declared public in that class.
-
An instance field can never be public. Classes with public mutable fields are not thread-safe. So that’s why I talked about why you can’t write a context in Android as public static context context; (Of course, for Android, private doesn’t work either, because context can’t be static). Instance field = instance field = instance field = instance field = instance field = instance field = instance field = instance field
-
The same advice applies to static domains.
In short, prevent any messy classes, interfaces, and members from becoming part of the API. Public classes should not contain Public fields, except in the special case of Public static final. Also make sure that objects in the public static final field are immutable. For example, you cannot define a public static final Things[] VALUES = {… }; Because non-zero arrays are mutable.