简体   繁体   中英

Why does an interface hosting main in Java 8 not have to be public?

Why does the following code compile and run successfully in Java 8+eclipse?

package package1;
interface A  
{
    static void main(String[] args) {
        System.out.println("Hi");
    }
}

If A is changed to a class, the run-time requires it to be a public class, but not so for an interface. This seems inconsistent.

EDIT: The above statment that I made when posting the question was WRONG . ( I must have been tired and misread the errors ). Java does NOT require the class hosting main to be public, only the method. However, it is a bit inconsistent that the type hosting main does not have to be public, while the main method does.

If A is changed to a class, the run-time requires it to be a public class.

No it doesn't. It requires the method to be public, and methods in interfaces already are public.

but not so for an interface.

Not so.

This seems inconsistent.

It isn't. You misread the error message.

In java prior to 1.8 static methods were not allowed.

All the methods were by default public, so you dont have to use the keyword explicitly.

interface myInterface {
public void show();
//same as above
 void show();
}

Starting from java 8, interfaces can also have static methods.

Therefore you can have static methods but dont require the public keyword

interface myInterface {
static void main(String[] args) {}
void show();
}

An interface and its fields and methods are always public.

If A is a class containing the main method, then A must be public. This is because the main method is always

public static void main(String[] args)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM