[英]Can interface type variable call methods from that interface in a class that doesn’t implement it?
I'm trying to understand this just for my own knowledge.我试图理解这一点只是为了我自己的知识。 Here is a broken down version of my code:这是我的代码的细分版本:
interface ILightningPhone {
void recharge();
void useLightning();
}
interface IMicroUsbPhone {
void recharge();
void useMicroUsb();
}
class LightningToMicroUsbAdapter implements IMicroUsbPhone {
private final ILightningPhone lightningPhone;
public LightningToMicroUsbAdapter(ILightningPhone lightningPhone) {
this.lightningPhone = lightningPhone;
}
@Override
public void useMicroUsb() {
System.out.println("MicroUsb connected");
lightningPhone.useLightning();
}
@Override
public void recharge() {
lightningPhone.recharge();
}
}
I'm trying to understand interfaces and I just need an explanation on the following:我正在尝试理解接口,我只需要对以下内容进行解释:
I notice that a variable private final ILightningPhone lightningPhone;
我注意到一个变量private final ILightningPhone lightningPhone;
is declared within a class of type ILightningPhone
interface.在ILightningPhone
接口类型的 class 中声明。 but this class doesn't implement that interface.但是这个 class 没有实现那个接口。 How is it able to do this?它是如何做到这一点的?
Next I notice that in the following method:接下来我注意到在以下方法中:
public void useMicroUsb() { System.out.println("MicroUsb connected"); lightningPhone.useLightning();
the variable lightningPhone
is able to call the useLightning()
method from the ILightningPhone
interface.变量lightningPhone
能够从ILightningPhone
接口调用useLightning()
方法。 Even though the ILightningPhone
interface is not implemented in the class LightningToMicroUsbAdapter
.即使ILightningPhone
接口未在 class LightningToMicroUsbAdapter
中实现。 Why is it able to do this?为什么它能够做到这一点?
Overall, I'm just trying to understand why we are able to create a variable of a interface type in a class that doesn't implement that interface?总的来说,我只是想了解为什么我们能够在不实现该接口的 class 中创建接口类型的变量? And why when declaring that variable of that interface type are we able to use the methods from that interface in a class that doesn't implement that interface?为什么在声明该接口类型的变量时,我们能够在未实现该接口的 class 中使用该接口中的方法?
Here is the full code if needed: https://en.wikipedia.org/wiki/Adapter_pattern如果需要,这是完整的代码: https://en.wikipedia.org/wiki/Adapter_pattern
The LightningToMicroUsbAdapter
class (or any class for that matter) can have any type of member - be it a String
, a List
, or even a ILightningPhone
. LightningToMicroUsbAdapter
class (或任何 class )可以有任何类型的成员 - 无论是String
, List
,甚至是ILightningPhone
。 Having a members is a "hasA" relationship, not an "isA" relationship.拥有成员是“hasA”关系,而不是“isA”关系。
Since the lightningPhone
is an instance of ILightningPhone
, it can call the useLightning
method defined by that interface.由于lightningPhone
是ILightningPhone
的一个实例,它可以调用该接口定义的useLightning
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.