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

Ahamed picture Ahamed · Sep 21, 2012 · Viewed 21.7k times · Source

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?

Answer

charles_ma picture charles_ma · Jul 24, 2013

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!