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

后端 未结 7 2142
半阙折子戏
半阙折子戏 2020-11-30 12:40

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 the

相关标签:
7条回答
  • 2020-11-30 13:27

    It's not a compile time error as u mentioned that top level type declaration shouldn't be protected, static or private.

    If u go through the link http://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.6 well that u have shared ,then it's quite clear there that a top-level type declaration refers to only "top level Class and Interface type declarations" and these should not be protected, static or private at top level declarations, but we can use protected, static or private for any methods or variable declaration inside them.

    With respect to above code, there is nothing wrong in declaration, and the code will compile and run successfully as all outer top level class are default and there is no violation.

    The answer to the question asked at top is exactly as mentioned by few experts at top, that

    "for sure we can have a file with main method inside non-public class and it will compile as well as run successfully, but make sure that at the time of running the program we have to pass the class name of "main method" to the java interpreter instead of the class which is public."

    If we have 2 classes A(public) and B(non-public containing main method) , then the file will compile with "javac A.java" but while running the code we need to pass the command as "java B" .

    0 讨论(0)
提交回复
热议问题