27

接口是一种特殊的类,还是说接口根本不是类?

4

7 回答 7

33

接口不是类,但您可以说接口和类都是类型

Java规范

在 Java 编程语言中,每个变量和每个表达式都有一个可以在编译时确定的类型。该类型可以是原始类型或引用类型。引用类型包括类类型和接口类型。

请注意,虽然有一个特殊的类Class<T>可以表示类和接口:

Class 类的实例表示正在运行的 Java 应用程序中的类和接口。

Class接口由实例表示isInterface的事实true可能会给您一种接口只是一种特殊类型的类的印象。然而,这种情况并非如此。

于 2012-07-30T11:15:11.823 回答
8

No, an interface is not a class in Java.

An interface is a type and all reference types (i.e. non-primitive types) handle quite similarly in Java. Often when people say "class" they are actually referring to a "reference type".

What might be confusing you is that an interface definition is stored in a .class file, but that's just a technical artifact of Java. In fact all reference type definitions (classes, interfaces, annotations, enums) are stored in .class files in Java.

于 2012-07-30T11:16:43.010 回答
7

接口的概念来自抽象类,其中抽象类包含方法(或抽象方法)的原型,并且也可以定义很少的方法,而接口包含方法或抽象方法的原型(或签名),其定义由实现类提供。因此,从上面的陈述可以清楚地看出,接口就像 100% 的抽象类,其中 没有定义任何方法。再次提到它,接口就像 100% 的抽象类,但不是类。

“接口是类可以做什么的契约”

引入接口的一个原因是,我们extend只能单个类,但是接口在java中带来了一个新的东西 implement,所以我们可以实现数千个接口。所以我们不能说它是一个类。

你可以在这里获得更多信息!

于 2012-07-30T11:34:52.177 回答
5

Interface is just a contract which all implementing classes should follow. An interface is something like a template which cannot make an impact until a class implements it.

于 2012-07-30T11:16:41.047 回答
3

Yes, an interface is an instance of java.lang.Class. If you have a Class you can interrogate it to see if it is an interface: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isInterface()

于 2012-07-30T11:16:56.300 回答
1

接口(是一组具有空主体的相关方法。)只是一个接口。它不是一个类(一个类是创建单个对象的蓝图)。

请注意,您定义了这样的接口

interface Bicycle {....}

一个类是这样定义的

class MyBMX implements Bicycle{...}

所以接口是接口而不是类

于 2012-07-30T11:17:55.760 回答
-4

是的,接口是一种类。简单地说,类方法和数据也存在于接口方法(仅抽象方法)和数据(仅静态和最终)中。

更多观看 https://www.youtube.com/watch?v=qgBv1_Plldo&list=PLbRMhDVUMngcx5xHChJ-f7ofxZI4JzuQR&index=21&t=13:52

于 2020-12-25T14:50:40.640 回答