The difference between public class and class
There are two ways to define a class:
- public class class name
- Class name
I can remove the public from the front of class, and if you declare class with the public class, then the file name must match the class name, which is the rule, what if the file name and class name are inconsistent? Let's change the file name of the previous Helloworld.java, for example, I changed to World.java, and then execute the javac command, you can see the following error message:
If a class is used to declare classes, the file name can be any legal filename, the filename does not need to be the same as the class class, and I remove the public from the code. The file name is still World.java, recompile with the Javac command, you can see that a new Helloworld.class file is generated, and then run Java HelloWorld, and you can see that the program is still working. One conclusion here is that the name of the class file compiled with the Javac command is not related to the Java filename, but is consistent with the class name.
In a Java file, you can declare multiple classes, but only one public class is declared, and the sample code:
After compiling with the Javac command, you will find that each class will generate a corresponding. class file
Java detailed analysis of class and public class differences