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

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

    Have a look at this code:
    Super.java

    public class Super{ }
    class Sub{
        public static void main(String[] s){
            System.out.println("Hello");
        }
    }
    

    In order to print Hello you can compile and run the program as:

    console output

    How this works?
    The compiler generates separate .class file for every class in your program. So, instead of calling the main() of non-public class from the public class's main() you can print the output as shown above.

    Note: As the convention says, you must put a public class in separate file .java. And do not put more than one class in a single file (except if they are inner class) because if you would like to import them or use them with other classes then it will cause problem.

提交回复
热议问题