简体   繁体   English

为什么Java 8中主要托管接口的接口不必公开?

[英]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? 为什么以下代码可以在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. 如果将A更改为类,则运行时要求它是公共类,但对于接口则不是。 This seems inconsistent. 这似乎不一致。

EDIT: The above statment that I made when posting the question was WRONG . 编辑:我在发布问题时做出的上述陈述是WRONG ( I must have been tired and misread the errors ). (我一定很累并且误读了错误)。 Java does NOT require the class hosting main to be public, only the method. Java不需要类宿主main是公共的,只要求方法是公共的。 However, it is a bit inconsistent that the type hosting main does not have to be public, while the main method does. 但是,类型托管主体不一定必须是公共的,而main方法却必须是公共的,这有点不一致。

If A is changed to a class, the run-time requires it to be a public class. 如果将A更改为类,则运行时要求它成为公共类。

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. 在1.8之前的Java中,不允许使用静态方法。

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. 从Java 8开始,接口也可以具有static方法。

Therefore you can have static methods but dont require the public keyword 因此,您可以使用static方法,但不需要public关键字

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. 如果A是包含main方法的类,则A必须是公共的。 This is because the main method is always 这是因为主要方法总是

public static void main(String[] args)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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