Reputation: 1498
I created the following Chimpazee.java
file with the following content:
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();
}
}
However, when I try to execute this file on Windows 10 + PowerShell using Java 11...
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)
I'm getting a runtime error with the following command
PS C:\projects\ocp-java-se\java-se-11\chapter8> java .\Chimpazee.java
error: can't find main(String[]) method in class: Primate
If I move the Chimpazee class to the beginning of the file it works fine. Isn't suppose to Java compile this independent of the sequence of the classes?
Upvotes: 5
Views: 506
Reputation: 79425
JEP 330 mentions it as:
The class to be executed is the first top-level class found in the source file. It must contain a declaration of the standard public static void main(String[]) method.
i.e. you need to make public class Chimpanzee
as the top-level class as follows:
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-");
}
}
Then, run it as
java Chimpanzee.java
Output:
Primate-Ape1-Chimpanzee-
Upvotes: 5