"Java Programming Ideas - Chapter 6 (Access Permission Control)"

access control

6.1 Packages: Library Units

A package contains a set of classes organized together under a single namespace.

6.2 Access modifiers

Package Access: All classes in the current package can be accessed.
public: All classes can access.
private: members of the free class can access it.
protected: inherited permissions. A base class can assign its access rights to derived classes instead of all classes.

Permissions in descending order: public——>protected——>package——>private

6.4 Class Access Rights

  1. There can only be one public class per compilation unit.
  2. The name of the public class must be the same as the class file name.
  3. The class can have no public class at all, and the file can be named arbitrarily.

Classes can only have package permissions or public permissions.

If the constructor is specified as private, others cannot create objects of this class. How can others get objects of this class?
You can create a static method that returns a reference to this class. (Singleton pattern)

Reasons to control access to members:
1) So that users don't touch parts they shouldn't touch.
2) Separation of interface and implementation, designers do not have to worry about affecting users when they change the class implementation.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325405973&siteId=291194637