java 接口没有构造函数,那怎么继承呢?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14709696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Interface does not have constructor, then how can it be inherited?
提问by Charan
As I know the subclass constructor calls the super class constructor by using super();
.
But since interface doesn't have any constructor, how can inheritance take place?
据我所知,子类构造函数使用super();
. 但是既然接口没有任何构造函数,那么继承怎么发生呢?
回答by Peter Lawrey
But since interface doesn't have any constructor how can inheritance take place??
但是既然接口没有任何构造函数,怎么继承呢??
Easy, an interface cannot have any instance fields so there is nothing to construct. You cannot place in code in an interface (up to Java 7 anyway) so there is nothing which needs to be called.
很简单,接口不能有任何实例字段,所以没有什么可构造的。您不能在接口中放置代码(无论如何直到 Java 7),因此不需要调用任何东西。
回答by Denys Séguret
The interface is a contract, defining what methods mush be offered by the implementation. A class doesn't inherit an interface but implements it.
接口是一个契约,定义了实现必须提供哪些方法。类不继承接口而是实现它。
From the specification:
从规范:
This type has no implementation, but otherwise unrelated classes can implement it by providing implementations for its abstract methods.
这种类型没有实现,但是不相关的类可以通过为其抽象方法提供实现来实现它。
回答by Fritz
Interfaces (also known as Service Contracts) are implemented, not constructed. They define a set of methods (Services) that a class provides, so a client knows what can he expect of the implementing class regardless of the actual type implementing the interface. The constructor is related to this particular instance of a given type, implementing the interface.
接口(也称为服务契约)是实现的,而不是构造的。它们定义了一个类提供的一组方法(服务),因此客户端知道他对实现类的期望,而不管实现接口的实际类型如何。构造函数与给定类型的这个特定实例相关,实现接口。
IYourObject yourObject = new YourObject();
On the other hand, interface inheritance is also by extension. It "adds" the methods of an interface to another one and allow the possibility of switching the interface type of an object amongst the different interfaces in the "hierarchy".
另一方面,接口继承也是通过扩展。它将一个接口的方法“添加”到另一个接口的方法,并允许在“层次结构”中的不同接口之间切换对象的接口类型。
回答by exexzian
Interface is not inherited - it is rather implemented
接口不是继承的 - 它是被实现的
回答by user7343218
Interface doesn't contain constructor because of the following reasons:
由于以下原因,接口不包含构造函数:
- The data member of the interface are already initialized .
- Constructors of the special defined methods which are not permitted to defined and moreover interface data member are static.
- 接口的数据成员已经初始化。
- 不允许定义的特殊定义方法的构造函数以及接口数据成员是静态的。