对“超级"感到困惑此Java示例中的关键字 [英] Confused about "super" keyword in this Java example
问题描述
在此示例中,位于Java网站的教程页面上.两个接口定义相同的默认方法startEngine()
.类FlyingCar
实现两个接口,并且由于明显的冲突而必须重写startEngine()
.
In this example on java website's tutorial page. Two interfaces define the same default method startEngine()
. A class FlyingCar
implements both interfaces and must override startEngine()
because of the obvious conflict.
public interface OperateCar {
// ...
default public int startEngine(EncryptedKey key) {
// Implementation
}
}
public interface FlyCar {
// ...
default public int startEngine(EncryptedKey key) {
// Implementation
}
}
public class FlyingCar implements OperateCar, FlyCar {
// ...
public int startEngine(EncryptedKey key) {
FlyCar.super.startEngine(key);
OperateCar.super.startEngine(key);
}
}
我不明白为什么从FlyingCar
中使用super
来引用OperateCar
和FlyCar
接口中的startEngine()
两个版本.据我了解,startEngine()
在任何超类中均未定义,因此不应被视为驻留在其中.我也没有看到super
与FlyingCar
I don't understand why, from FlyingCar
, super
is used to refer to both versions of startEngine()
in OperateCar
and FlyCar
interfaces. As I understand it, startEngine()
was not defined in any super class, therefore shouldn't be referred as resident in one. I also do not see any relationship between super
and the two interfaces as implemented in FlyingCar
推荐答案
据我了解,startEngine()未在任何超类中定义,因此不应被视为驻留在其中.
As I understand it, startEngine() was not defined in any super class, therefore shouldn't be referred as resident in one.
是的,它已定义.这是默认的实现,例如:
Yes it was defined. It's the default implementation, for example:
public interface OperateCar {
// ...
default public int startEngine(EncryptedKey key) {
// Implementation
}
}
OperateCar.super.startEngine(key)
将执行默认实现.
如果没有默认实现,则只是一个接口方法, 那么该语句就没有意义,因为该接口将不包含实现,例如:
If there was no default implementation, just an interface method, then the statement wouldn't make sense, as the interface wouldn't contain an implementation, like this:
public interface OperateCar {
// ...
int startEngine(EncryptedKey key);
}
我也没有看到在FlyingCar中实现的super和两个接口之间的任何关系
I also do not see any relationship between super and the two interfaces as implemented in FlyingCar
不确定我了解您的要求.
super
是在父接口中调用实现的方法.
没有super
,就没有其他表达方式.
Not sure I understand what you're asking.
super
is a way to call the implementation in the parent interface.
Without super
, there's just no other way to express that.
这篇关于对“超级"感到困惑此Java示例中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!