根据java教程https://docs.oracle.com/javase/tutorial/java/javaOO/classdecl.html
You can also add modifiers like public or private at the very beginning—so you can see that the opening line of a class declaration can become quite complicated. The modifiers public and private, which determine what other classes can access MyClass, are discussed later in this lesson. The lesson on interfaces and inheritance will explain how and why you would use the extends and implements keywords in a class declaration. For the moment you do not need to worry about these extra complications.
In general, class declarations can include these components, in order:
- Modifiers such as public, private, and a number of others that you will encounter later.
- The class name, with the initial letter capitalized by convention.
- The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
- A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
- The class body, surrounded by braces, {}.
但是当使用 private 修饰符声明类(顶级类)时,编译器会提示一条消息 Modifier 'private' not allowed here。
这是我的代码
private class MyPrivateClass {
}
以及编译时的错误信息
1: error: modifier private not allowed here
最佳答案
来自section 8.1.1 of the Java Language Specification (JLS) :
The access modifiers
protected
andprivate
pertain only to member classes within a directly enclosing class or enum declaration.
换句话说,私有(private)类只有包含在另一个类中时才被允许。
关于java - 将java类声明为私有(private)触发编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48851925/