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

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

    there is something i would like to add although everybody here believes that a public is necessary for the main in a class and that it won't work without main

    you can have as many mains in a class as you desire, and you can have them without a public access modifier. but be careful, only that class which is named after the file can be public what i mean is if you name your file a.java , then only the class with name a can be public, none other can have this facility

    here is a code to show this : as you can see the name of the file is helping.java

    //:initialization/helping.java
    
    class b{
        public static void main(){
            System.out.println("hello its b");
        }
    }   
    
    class helping {
        static void f(float i, Character... c) {
            System.out.println("first");
        }
        static void f(char a, Character... args) {
            System.out.println("second");
        }
        public static void main(String[] args) {
            f(1,'a');
            f('a','b');
            c.main();
        }
    }
    
    class c{
        public static void main(){
            System.out.println("hello its b");
        }
    }
    //:~
    /*
     * output:  
     * first
     * second
     * hello its b  
     * */
    

提交回复
热议问题