问题描述
为什么接口允许在Java 8中使用 main
方法?
Why are interfaces allowed to have a main
method in Java 8?
如下面的代码中所述工作正常并正确生成输出。
As stated in below code it works fine and produces output properly.
public interface Temp {
public static void main(String args[]){
System.out.println("Hello");
}
}
目前它表现得像一个类,我已执行使用main方法接口
。
Currently it is behaving like a class and I have executed interface
with main method.
为什么我们需要这个?
推荐答案
从Java 8开始,接口中允许使用静态方法。
Since Java 8, static methods are allowed in interfaces.
main()是一种静态方法。
main() is a static method.
因此,接口允许使用main()。
Hence, main() is allowed in interfaces.
我们不需要这个,因为以前不允许,但我们幸存了下来。但是,根据定义,静态方法不是绑定到类的实例,而是绑定到类本身,因此在接口中允许它们是有意义的。它允许在接口本身中定义与接口相关的实用程序方法(例如,在 Collections
中找到的),而不是单独的类。)
We don't need this, since it wasn't allowed before, and yet we survived. But since static methods, by definition, are not bound to an instance of a class, but to the class itself, it makes sense to allow them in interfaces. It allows defining utility methods related to an interface (like the ones found in Collections
, for example), in the interface itself, rather than a separate class).
类静态方法和接口静态方法之间没有区别。
There is no difference between class static methods and interface static methods.
这篇关于为什么Java 8中的接口允许使用main方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!