gpt4 book ai didi

如果未首先声明公共(public)类,则 Java 11 不会运行 main 方法

转载 作者:行者123 更新时间:2023-12-04 11:22:46 26 4
gpt4 key购买 nike

我创建了以下 Chimpazee.java包含以下内容的文件:

class Primate {
public Primate() {
System.out.print("Primate-");
}
}

class Ape extends Primate {
public Ape(int fur) {
System.out.print("Ape1-");
}
public Ape() {
System.out.print("Ape2-");
}
}

public class Chimpazee extends Ape {
public Chimpazee() {
super(2);
System.out.print("Chimpazee-");
}
public static void main(String[] args) {
new Chimpazee();
}
}
但是,当我尝试使用 Java 11 在 Windows 10 + PowerShell 上执行此文件时...
PS C:\projects\ocp-java-se\java-se-11\chapter8> java -version
java version "11.0.11" 2021-04-20 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)
我使用以下命令收到运行时错误
PS C:\projects\ocp-java-se\java-se-11\chapter8> java .\Chimpazee.java
error: can't find main(String[]) method in class: Primate
如果我将 Chimpazee 类移动到文件的开头,它工作正常。是不是假设 Java 编译这个与类的顺序无关?

最佳答案

JEP 330提到它:

The class to be executed is the first top-level class found in thesource file. It must contain a declaration of the standard publicstatic void main(String[]) method.


即您需要制作 public class Chimpanzee作为顶级类如下:
public class Chimpanzee extends Ape {
public Chimpanzee() {
super(2);
System.out.print("Chimpanzee-");
}
public static void main(String[] args) {
new Chimpanzee();
}
}

class Primate {
public Primate() {
System.out.print("Primate-");
}
}

class Ape extends Primate {
public Ape(int fur) {
System.out.print("Ape1-");
}
public Ape() {
System.out.print("Ape2-");
}
}
然后,运行它
java Chimpanzee.java
输出:
Primate-Ape1-Chimpanzee-

关于如果未首先声明公共(public)类,则 Java 11 不会运行 main 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68307685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com