On Top level Class Decoration in Java

  • 2021-12-09 08:57:33
  • OfStack

Directory Java top-level class decoration problem is sorted out today, but why is this the case? private cannot be used to decorate top-level class reasons

Java Top Level Class Decoration Problem

For this problem, 1 has not thought carefully

Tidy it up for 1 time 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, 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.

private cannot be used to decorate top-level classes

Cause

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 kinds of control permissions are needed: package control permissions and public access permissions.

This corresponds to two control modifiers: public and default (default).

But private can decorate class's, except that this class does not make the top-level class,

It can be an internal class. The upper level of an internal class is an external 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 this class


Related articles: