There can be at most one public class in a Java source file,
1) When there is a public class, the source file name must be the same , or it cannot be compiled,
2) If there is no public class in the source file, there is no consistency requirement in the file name and class.
The main () does not have to be placed in the public class to run the program.
Note:
First:
Test7.java source file: Class test5{ int i = 1;} public class test6{ int i = 2; public static void main (string[] args) {System.out.println ("Main method");}}
Error running Test7.java because there is a problem in the main class, that is, the class name Test6 and the file name Test7 are not the same in the public class, so there is an error. Indicates that the file name must match the class name of the public class (if there is a public class in the file)
Second:
class test1{ int i = 1;} class test2{ int i = 2; Public Static void Main (string[] args) { System.out.println ("Main method");} }
Run Test3.java Result: run Test2 because there is no Test3.class file generation , and here also shows that the class containing the main () if you want to run it is not necessarily public.
Correction: Test3.java source file:
class test1{
int i=0;
}
class test3{
int i = 2 ;
Public Static void Main (string[] args) {
System.out.println ("Main method");
}
}
Run the corrected Test3.java result: Run successfully
7th. There can be only one public class in a Java source file