Explain why the external classes of Java can not be decorated with private and protected

  • 2021-07-18 07:54:34
  • OfStack

Why can't the external classes of Java be decorated with private and protected

For this problem, I didn't think carefully, so I sorted it out today:

For top-level classes (external classes), there are only two modifiers: public And default ( default ). Because the top 1 unit of an external class is a package, the external class has only two scopes: the same package, anywhere. Therefore, only two types of control permissions are required: package control and public access, which correspond to two types of control modifiers: public and default (default).

If the class uses the private Modifier to indicate that it is an inner class. The upper level of the inner class is the outer class, so there are four kinds of access control modifiers: this class (private), the same package (default), the parent-child class (protected), and anywhere (public). When an inner class is decorated with private, it can only be used inside the outer class of the class.

These are common to use at ordinary times, but why is this the case?

It is possible to think that an java project cannot be completed in an class. In mvc mode, the class is divided into three layers, and one layer calls the class. If defined as private and protected, it cannot be called. In other words, for an java file, either it runs alone or is called by other programs as a library. If the class of an java file is modified by private, is it impossible for other programs or classes to use it, and it is useless as a separate file? If it runs as a single file, how can class loading find it because it is invisible to the outside world? At the same time, it also loses the meaning of class. Therefore, the class only has public and default modifiers.

Summary

1. Class refers to external class, the largest class, and its modifiers are public (indicating that this class can be imported in all classes of the project), default (this class can only be used in the same package), abstract , final

2. Inner class refers to a named class that lies inside a class but does not include a class that lies inside a block, constructor, or method. The modifiers are public , private , protected Access control characters, you can also use static , final Keyword modification, public and private are relatively simple, one means that all can be accessed by all classes, one means that it can only be accessed by itself, and the member classes modified by protected can be accessed by classes and subclasses in the same package. And default Modified member classes can only be accessed by classes in the same package.

3. Local inner classes refer to named classes located in blocks, constructors and methods, and can only have at most final Modify

Summarize


Related articles: