对“超级"感到困惑此Java示例中的关键字 [英] Confused about "super" keyword in this Java example

查看:112
本文介绍了对“超级"感到困惑此Java示例中的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此示例中,位于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来引用OperateCarFlyCar接口中的startEngine()两个版本.据我了解,startEngine()在任何超类中均未定义,因此不应被视为驻留在其中.我也没有看到superFlyingCar

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆