gpt4 book ai didi

java - 接口(interface)作为Java中的一种类型?

转载 作者:IT老高 更新时间:2023-10-28 20:59:30 27 4
gpt4 key购买 nike

来自 The Java Tutorials :

In Java, a class can inherit from only one class but it can implement more than one interface. Therefore, objects can have multiple types: the type of their own class and the types of all the interfaces that they implement. This means that if a variable is declared to be the type of an interface, its value can reference any object that is instantiated from any class that implements the interface.

谁能为此提供一个基本的伪类型。我没看懂粗线。

最佳答案

让我们声明两个接口(interface)和一个实现它们的类:

interface I1 { }

interface I2 { }

class C implements I1, I2 { }

objects can have multiple types

在下面的代码中,可以看出C实例的类型为 C以及 I1I2 :

C c = new C();

boolean isC = (c instanceof C); //true
boolean isI1 = (c instanceof I1); //true
boolean isI2 = (c instanceof I2); //true

现在让我们声明一个类 B实现I1还有:

class B implements I1 { }

if a variable is declared to be the type of an interface, its value can reference any object that is instantiated from any class that implements the interface.

如果我们声明 I1 类型的变量,我们可以将其设置为 C 的实例,然后将其重新分配给 B 的实例:

I1 i1 = new C();
i1 = new B();

我们还可以将它重新分配给 D 的实例, 其中 D延长 C :

i1 = new D();

...

class D extends C { }

关于java - 接口(interface)作为Java中的一种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7275844/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com