Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

main

public

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?

like image 777
Ahamed Avatar asked Sep 21 '12 04:09

Ahamed


People also ask

Can main method be in non public class?

Yes, we can declare the main method as private in Java. It compiles successfully without any errors but at the runtime, it says that the main method is not public.

What if the main method is not public in Java?

Declaring the main method private or, protected But, at the time of execution JVM does not consider this as the entry point of the program. It searches for the main method which is public, static, with return type void, and a String array as an argument. If such a method is not found, a run time error is generated.

Can we write main method without public in Java?

Yes. Things like libraries don't have a main method. The main method is the entry point for the program, so you'll have to have a main method somewhere or the code won't execute, but not necessarily in any given Java file.

Can we access main method from outside class Java?

Though Java doesn't prefer main() method called from somewhere else in the program, it does not prohibit one from doing it as well. So, in fact, we can call the main() method whenever and wherever we need to.


1 Answers

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  
 * */
like image 174
user2440665 Avatar answered Sep 18 '22 18:09

user2440665