2

So I was reading following article:

https://dzone.com/articles/why-single-java-source-file-can-not-have-more-than

On the topic of why we cant have more than one public class in one file and there was this statement:

And also as soon as we execute our application, JVM by default looks for the public class (since there are no restrictions and it can be accessible from anywhere), and it also looks for public static void main(String args[]) in that public class. The public class acts as the initial class from where the JVM instance for the Java application (program) is begun. So when we provide more than one public class in a program the compiler itself stops you by throwing an error. This is because later we can’t confuse the JVM as to which class is to be its initial class, because only one public class with the public static void main(String args[]) is the initial class for JVM.

This confuses me because of following reasons:

  1. When we compile the code compiler would create seperate .class files for every class
  2. When we execute the code we are telling JVM in which class the main method is example java Test (where Test is an .class file) which means that jvm only has to look if the main method is defined inside this .class file

So what does the statement means that JVM looks for main method inside public classes?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    *we can't have more than one public class in one file* isn't strictly accurate without more qualification. You can have multiple public classes in the same file (just not multiple top-level public classes in the same file) – ernest_k Nov 21 '19 at 06:35
  • Does [this](https://stackoverflow.com/questions/3578490/why-only-1-public-class-in-java-file) answer your question? – Sweeper Nov 21 '19 at 06:43
  • Does this answer your question? [How does the JVM use the "Main method" to start a Java program?](https://stackoverflow.com/questions/4446542/how-does-the-jvm-use-the-main-method-to-start-a-java-program) – Thihara Nov 21 '19 at 06:44
  • 1
    Your confusion is justified. The justification given in the article doesn't make any sense. The Java designers just decided that it was illegal to have several top-level public classes in the same file, and that each top-level public class must be in its own file, named after the name of the class. Other JVM languages decided differently. – JB Nizet Nov 21 '19 at 06:45
  • 1
    Whatever it might mean, it's wrong. The `main()` method to be executed doesn't have to be in a public class. Don't rely on third-party Internet junk. Use the reference material provided with Java. – user207421 Nov 21 '19 at 09:02

0 Answers0