No. A Java file does not need a public top-level class to compile or run.
For example, this is valid:
class Hello {
public static void main(String[] args) {
System.out.println("Hello");
}
}
You can save it as:
Main.java
and run:
javac Main.java
java Hello
But remember
If you have a public class:
public class Main {
}
then the filename must match:
Main.java
If there is no public class, the filename doesn't have to match any class name.
For example:
class Animal {
}
class Hello {
public static void main(String[] args) {
System.out.println("Hello");
}
}
can technically be saved as Anything.java, compiled, and then run with:
java Hello
Simple rule
A Java file doesn't require a public class. It only needs a class containing
main()if you want to run it as a program.
And if you have a public class, the filename must match that public class.