Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why main method can't be of default scope? [duplicate]

Tags:

java

If we declare the class with default scope(non-public) and public main method it executes successfully. Here class scope is mote stricter than main method scope.

But if we declare main method as default, then JVM will throw error. Why?

class DefaultTest {
    public static void main(String[] args) {
        System.out.println("output.........");
    }
}

Runs successfully but

class DefaultTest {
    static void main(String[] args) {
        System.out.println("output.........");
    }
}

this won't.

I mean if the class itself is not public JVM can still access main method that means there is no need of main to be public. But if we don't declare it as public, it will throw an error.

like image 586
Ninja Avatar asked Dec 25 '13 20:12

Ninja


People also ask

Can we declare main method as default?

You can define the main method in your program without private, protected or, default (none) modifier, the program gets compiled without compilation errors. But, at the time of execution JVM does not consider this as the entry point of the program.

Why main () method is public in Java?

Why is main method public in Java? We know that anyone can access/invoke a method having public access specifier. The main method is public in Java because it has to be invoked by the JVM. So, if main() is not public in Java, the JVM won't call it.

Why this keyword is not used in main method?

Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method. If you still, try to do so a compile time error is generated. And main method is static therefore, you cannot use the "this" reference in main method.

Can we declare main method as a private?

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.


2 Answers

It is specified by the Java Language Specification, see http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html chapter 12.1.4. Invoke Test.main:

The method main must be declared public, static, and void.

It is also required by the JVM specification, see the answer from @A4L.

like image 155
Andreas Fester Avatar answered Oct 11 '22 12:10

Andreas Fester


static so that the JVM can run the method without having to instantiate the class object + public so that the JVM can access it freely without any access issues.

like image 26
Kick Buttowski Avatar answered Oct 11 '22 12:10

Kick Buttowski