简体   繁体   English

说接口也是一种类型是什么意思?

[英]What does it mean to say that an interface is also a type?

I think that it means that via the concept of polymorphism, a variable's type can be declared to be that of an interface. 我认为这意味着通过多态的概念,可以将变量的类型声明为接口的类型。 For ex: if Animal is an interface, you could code the following: 例如:如果Animal是一个接口,您可以编写以下代码:

Animal simba = new Lion();

Am I correct in my understanding of this? 我对此的理解是否正确? Thanks for any help. 谢谢你的帮助。

An interface can act similarly to a superclass in Java, in that it can take on the type of its implementations. interface可以类似于Java中的superclass ,因为它可以采用其实现的类型。

In your example, specifically, you define Animal as an interface which Lion implements. 在您的示例中,具体而言,您将Animal定义为Lion实现的interface

Because of this, you can create an Animal of type Lion . 因此,您可以创建Lion类型的Animal The code would look like this: 代码如下所示:

interface Animal {
  //do interfacing stuff
}

class Lion implements Animal {
  public Lion() {
    //...
  }
  //do implementing stuff
}

class Driver {
  Animal simba = new Lion(); // This works because of polymorphism.
}

You are correct, though, in saying that this is an example of polymorphism . 但是,你说这是多态性的一个例子是正确的。

Every object has a type (and a value).* There are many types: primitive types (like int ), class types (like string ), enums, arrays (and perhaps I'm forgetting some). 每个对象都有一个类型 (和一个值)。*有许多类型:基本类型(如int ),类类型(如string ),枚举,数组(也许我忘了一些)。

The term "interface" refers to a particular sort of class type: it is a class which has no member objects (safe constants) and only public methods, all of which are abstract .** 术语“接口”指的是一种特殊的类类型:它是一个没有成员对象(安全常量)的类,只有公共方法,所有这些都是抽象的 。**

So: an interface is a special sort of class, which in turn is a special sort of type. 所以:接口是一种特殊的类,它又是一种特殊的类型。 So interfaces are types. 所以接口类型。 In your example, both Animal and Lion are types, and one happens to be convertible to the other. 在您的示例中, AnimalLion都是类型,一个恰好可以转换为另一个。

*) Loosely, the type says "what is the structure of this", and the value says "what is the content of this". *)松散地,类型说“这是什么结构”,价值说“这是什么内容”。 The type of 5 is int , and its value is... well, 5. 5的类型是int ,它的值是......好吧,5。

**) This enables you to inherit from multiple interfaces , while it is not possible in Java to inherit from multiple general classes. **)这使您可以从多个接口继承,而在Java中不可能从多个通用类继承。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM