接口作为Java中的一种类型? [英] Interface as a type in Java?

查看:394
本文介绍了接口作为Java中的一种类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Java教程


在Java中,一个类只能从一个类继承,但它可以实现
多个接口。因此,对象可以有多种类型
它们自己的类的类型以及它们实现的
所有接口的类型。这意味着如果变量被声明为接口的
类型,则其值可以引用从实现接口
的任何类实例化的
对象。

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.

任何人都可以为我提供一个基本的伪类型。我不明白粗线。

Can anyone provide me a basic pseudo type for this. I did not understand the bold lines.

推荐答案

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

Let's declare two interfaces and a class that implements them both:

interface I1 { }

interface I2 { }

class C implements I1, I2 { }




对象可以有多种类型

在下面的代码中,可以看到 C 实例具有类型 C 以及 I1 I2

In the following code, it can be seen that a C instance has the type of C as well as I1 and I2:

C c = new C();

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

现在让我们声明一个类 B 也实现 I1

Now let's declare a class B which implements I1 as well:

class B implements I1 { }




如果变量被声明为一个类型接口,它的值可以引用从实现接口的任何类实例化的任何对象。

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

If we declare a variable of type I1, we can set it to an instance of C, and then reassign it to an instance of B:

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

我们还可以将其重新分配给 D ,其中 D extends C

We can also reassign it to an instance of D, where D extends C:

i1 = new D();

...

class D extends C { }

这篇关于接口作为Java中的一种类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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