Home >Java >Javagetting Started >Is there a public class required in a java source file?
Yes, there can be only one public class in a source file. Because each compilation unit (file) can only have one public class, that is, each compilation unit has a single public interface, represented by a public class; this interface can contain numerous classes that support package access permissions as required.
The operating environment of this tutorial: windows10 system, java8, Dell G3 computer.
Question: Can a ".java" source file include multiple classes (not inner classes)? What are the restrictions?
Answer: There can be multiple classes, but there can only be one public class, and the public class name must be consistent with the file name. There can be only non-public classes in a file. If there is only one non-public class, this class can be different from the file name.
Why can there be only one public class in a java source file?
There are three paragraphs like this in the book Java Programming Thoughts (Fourth Edition) (6.4 Class Access Permissions):
1. Each compilation unit (file) has There can only be one public class, which means that each compilation unit has a single public interface, represented by a public class. This interface can contain as many classes as required to support package access. If there is more than one public class in a compilation unit, the compiler will give an error message.
2. The name of the public class must be exactly the same as the name of the file containing the compilation unit, including upper and lower case. If they don't match, you'll also get a compilation error.
3. Although it is not very common, it is possible to have no public classes in the compilation unit at all. In this case, you can name the file whatever you want.
What happens when there is no public class in the java source file?
At this time, the program is compiled and three .class files are generated under the corresponding path. If you click Run directly, the program will not run. We need to right-click the program----->Run As----->Java Aplication----->Select the data source
Personal summary:
A compilation unit (java file) can have multiple classes, and multiple different .classes are generated during compilation. Files and .class files are the source of data for program operation. Java uses public classes as the data interface of each compilation unit. There can only be one, otherwise it cannot handle java files with multiple classes. When a compilation unit (java file) has multiple non-public classes, the data source needs to be selected at runtime.
Recommended related video tutorials: Java video tutorial
The above is the detailed content of Is there a public class required in a java source file?. For more information, please follow other related articles on the PHP Chinese website!