java - 将java类声明为私有(private)触发编译错误

标签 java

根据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:

  1. Modifiers such as public, private, and a number of others that you will encounter later.
  2. The class name, with the initial letter capitalized by convention.
  3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  4. 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.
  5. 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 and private pertain only to member classes within a directly enclosing class or enum declaration.

换句话说,私有(private)类只有包含在另一个类中时才被允许。

关于java - 将java类声明为私有(private)触发编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48851925/

相关文章:

java - 为 Kotlin 创建 POJO 类

java - 强制更新 UI

java - Jasper Report—— HashMap 或子报告

java - (JavaFX) 如何使用基本 java 类更改 fxml 文件中编码的 ImageView 中的图片?

java - 是否可以使用 SQL Server JDBC 驱动程序进行代理身份验证?

java - 抽象类的具体子类作为原始类中的参数,没有抽象方法实现

java - 如何在使用自己的证书时启用 PDF LTV 签名 (Adobe java PDFBox)

java - Apache 汤姆霍克 <t :inputFileUpload> tag not working

java - 在 Windows 7(64 位)上,是否只需要安装 64 位 Java 和 64 位 Eclipse?

java - 更新(未设置)Android Firebase 子数据