why should Java only allow ONE public class in a java source file ,and if the class is declared "public"，why the filename should the same with the public class name? Is it true: in our programming ,we only use the .class file ,not the .java file,so it is not important about the rule on .java.But it seems Sun doesn't think so. every useful answers are welcome.thanks a lot!
This goes back to Oak was done to make it easier for the compiler to find and compile dependent classes. In other words, suppose while compiling your program the compiler finds a reference to a class named FindMe. Assuming there is no class file named FindMe.class, the compiler will try to find it in order to compile it for you. But what should it look for? It will look for FindMe.java. So the only reason is so that the compiler can find and compile dependent classes without having to search through every .java file.
Well according to me the public class name should be the name of the java file is not a compiler rule though Sun recommends it. It is up to the compiler to enforce the rule or not. That is, a compiler developer can disregard this rule. Well I think that its really useful to keep the class name as the name of the file as in case someone wants to know what a specific file does or wants to look what methods does a class have it becomes much easier. I find it better to keep non public java files in their class named file as well. [ May 16, 2003: Message edited by: Anupam Sinha ]
Joined: Apr 13, 2003
But another scene is :when there is a "public" class in a java file, then you must create the "main" method in this class,not the other "non-public"class.So why? I think the position of "main" method doesn't matter with the access control modifiers!
This is not true. Consider this :
Compile it and name it test.java. As test is a public class. Compile the file. It will create two files test.class and test1.class. The command line java is used to start a class's main() maethod. So when you do java test it will give you an error because it doesn't has a main method. Instead you should do java test1 which would then execute the required file. If you want both the classes can have a main method and you can decide which one you want to execute.
Joined: Oct 26, 2002
Ok,thanks anyway,I already got your point! But why two "Public" class are not allowed in ONE java file?I think it should not matter with the access modifier"public".
Joined: May 05, 2000
Originally posted by Daniel Washington: But why two "Public" class are not allowed in ONE java file?