-1

Please explain me some Java basics.

  1. Why is it required for a java file to have a same-named class inside of it? What if there is no class with such name inside of it?
  2. If a file contains several classes with main() method inside of them, which one will be selected when launching the file? And again, what if there's no such method in any class of the file?
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
Juggernaut
  • 315
  • 1
  • 3
  • 9
  • 1
    *"1. Why is it required for a java file to have a same-named class inside of it?"* Language design choice; 1a Try it. *"2. If a file contains several classes with main() method inside of them, which one will be selected when launching the file?"* That depends on how you call the class from the CLI; 2a It will fail to run, cause you must have a `main` method, assuming you are specifying it as the main class for the JVM to execute – MadProgrammer Nov 17 '14 at 05:35
  • You don't need a main, thats just the usual entry point from java runners. If you use a different runner, you need to offer different entry points. For instance, junit uses annotations to indicate which methods to run. Maven surefire can call just about any method you include. Eclipse can call directly to methods, or use junit/maven as runners. – CharlieS Nov 17 '14 at 05:50

2 Answers2

2
  1. Because the Java designers thought it would be a good convention and would make the developer life easier if the class Apple was defined in Apple.java rather than Banana.java.
  2. You never pass a file name to the java executor. You pass it a class name, like com.mycompany.myproject.MyMain. If this class doesn't have a main method, java will display an error message.
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

Why is it required for a java file to have a same-named class inside of it? What if there is no class with such name inside of it?

Because java compiler needs to start the execution from the public class inside the .java file . You can have any number of class inside , but only one public class with the name of the program

If a file contains several classes with main() method inside of them, which one will be selected when launching the file? And again, what if there's no such method in any class of the file?

Try it yourselves , you can overload the main() in a class. It will start execution from default . Have a look at Multiple main() methods in java and also Use of class definitions inside a method in Java to get some clear understandig

Community
  • 1
  • 1
Santhosh
  • 8,181
  • 4
  • 29
  • 56