首先,要明确的是,我知道什么是接口(interface)。
我的意思是,我可以要求实现该接口(interface)的类具有接口(interface)中提到的构造函数吗?
如下:
public interface IA {
/*constructor requirement*/
public IA(int, int, int, int, int, int, int);
}
public class A implements IA {
/* Because I implements IA, I have to make this contructor */
public A(int, int, int, int, int, int, int) {
....
}
}
最佳答案
不允许在接口(interface)中指定构造函数。这是不允许的,因为构造函数不是继承的。如果父类(super class)具有构造函数 Superclass(int, int, int)
,则不会强制子类具有构造函数 Subclass(int, int, int)
。因此,接口(interface)也不应该能够强制构造函数。
JLS, Section 9.1.4 ,说明接口(interface)体内可以存在的唯一事物:]
The body of an interface may declare members of the interface, that is, fields (§9.3), methods (§9.4), classes (§9.5), and interfaces (§9.5).
InterfaceBody: { InterfaceMemberDeclarationsopt } InterfaceMemberDeclarations: InterfaceMemberDeclaration InterfaceMemberDeclarations InterfaceMemberDeclaration InterfaceMemberDeclaration: ConstantDeclaration AbstractMethodDeclaration ClassDeclaration InterfaceDeclaration ;
这意味着 Java 明确不允许在接口(interface)中使用构造函数; JLS 不会在可以成为接口(interface)成员的事物列表中列出构造函数。
关于java - 接口(interface)中构造函数的要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21610516/