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

后端 未结 7 2168
半阙折子戏
半阙折子戏 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:02

    Actually you can execute the main method in a non-public class. if you put this class

    class A {
      public static void main(String... args) {
          System.out.println("This is not a public class!");
      }
    }
    

    in a file named NonPubClass.java. You can compile this file using javac command but you will not get a NonPubClass.class, you will get a A.class instead. Use java a to invoke that class and you will see the printed string --- This is not a public class!

提交回复
热议问题