• Post Reply Bookmark Topic Watch Topic
  • New Topic

public void static main(String[] args]  RSS feed

 
Andree Charfen
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok... I thought that a class had to be public, had the same name of the class and have the correct signature for running the static void main method. So.. I am experimenting and here is file called Test.java:

which one is getting called? Well sometimes a, sometimes b!!! None of them are publi and none of them have the name of the file! What is this?!?!
 
Joe Ess
Bartender
Posts: 9439
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can declare any number of classes in a single .java file. Only one class can be declared public. Declaring a class as public makes it available outside of the package that it is declared in (if you don't use the package statement, a class is put in the default anonymous package). If a class is declared public, the file name must match the public class name. The only reason I can think for this restriction is to make it easy to track down where the public classes (which make up the public view of a package) are declared.
In your example, telling the virtual machine to run test3 (java test3) should print out "a" and running test4 (java test4) should print out "b". This is because running "java classname" simply tells the virtual machine to load the class classname and call its "public static void main(String[] args)" method. This has nothing to do with if the class is public or not.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're confusing several different things here; let me try to clear things up.
The Java launcher doesn't accept a Java file as input; it accepts a class, at which point the fact that there were multiple classes defined in a single source file is irrelevant. If you've got some sort of funky IDE that lets you "launch" a source file, and chooses randomly among the classes in that file, then I'd advise you to ditch it and use something a bit less flaky.
I'm not aware of any stated requirement that a class with a main routine must be public; if it's in the default package, the class will be accessible whether it's public or not.
The JLS does require that there can be no more than one public class in a translation unit (i.e., in a Java file.) There's no absolute requirement about the name of a public class matching the name of the file, though -- but basically all Java compilers want that, because it makes compiling groups of classes much easier.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!