public interface Drive {
int getNumWheels();
default int driveMiles(){
return 10;
}
static int getColorID(){
return 0;
}
}
在上面的代码中,为什么接口(interface)中的静态方法不需要默认访问修饰符?我知道JDK 8中添加了默认方法,并提供了可选的实现,但是,我对静态方法有点不清楚?这看起来真的很像类的静态方法?
最佳答案
In the code above, why doesn't the static method in an interface not need a default access modifier?
我猜你是在问,为什么它是static
而不是static default
?
在类中,您可以只使用static
,而且他们很可能认为保持一致会更简单。
This seems really similar to a class's static method?
这就是为什么我相信语法是相同的。
<小时/>更好的问题是
why do we use
default
as a modifier at all?
我能想到的有两个原因
default
已经是一个很容易在语言中重用的关键字,并且在注释中以类似的方式使用它。- 它清楚地表明该方法旨在有一个实现。他们本可以完全不需要关键字,但一点冗余可以提高代码质量。
why did they decide to include static in an interface for JDK 8?
其好处与类
相同。您可以定义与接口(interface)关联但不依赖于特定类的方法。一个很好的例子是工厂类。过去你必须说
Logger LOGGER = LoggerFactory.getLogger(...);
如果您希望 Logger 成为一个接口(interface)
,它就是工厂方法,它必须是静态
,必须使用实用程序类。现在您的 API 可能是
Logger LOGGER = Logger.get(...);
工厂方法的接口(interface)
与其返回的接口(interface)相同,因此没有理由精确确定get
返回的类型。
关于java - 为什么接口(interface)中的静态方法不需要默认访问修饰符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36787211/