Search code examples
javaprogram-entry-pointpublic

What if main method is inside "non public class" of java file?


I have a java file containing more than one class, out of which one is public. If main method is inside a non-public class. I can't run that java file. Why is that? and there is no compilation error as well. If so, how can I use that main method?


Solution

  • You can certainly override main method and it does not violate any compiler rules and hence you will not have any compiler errors.

    You check that inspite of the fact that you have more than one class a file that is declared as public is the name of the file you are trying to execute.

    This is a convention that the file should be named after the same class which is public in that code.

    Hence when you try to execute that class it does not have a main method from which it starts execution.So if you want to execute the main method in the non public class the only way to this is call that main from a main method of the public class.