We can only have one top level public class or interface in any java compiler (source .java file).
But there can be any number of default classes / interfaces for the src file.
why:
JLS leaves the java compiler option. And most compiler implementations force you to have a file name just like:
(1) public class / interface name
(2) if there is a main method and there is no public class, then any name
(3) If there is a main method and an open class, then the main method should be in this open class
(4) if there is no public class and no main method, then any valid name that may or may not match the class / interface names in the file.
From (2): If two public classes are acceptable, we must provide the file with two names that are terribly pointless for the file system. From (3): If two public classes are acceptable, we should have two main methods that are terribly pointless for java
Therefore, a Java source file can have only one public class.
I think that the above 4 points forced the compiler to do the work of both the compiler and jvm in order to find a specific java source file or class file, simple and quick to compile / load / link. Java has such built-in restrictions that developers must adhere to in order to have better programming.
Source: My readings and understanding.
Venkataswamy Feb 07 '14 at 10:26 2014-02-07 10:26
source share