java - 接口(interface)中构造函数的要求

标签 java android interface constructor enums

首先,要明确的是,我知道什么是接口(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/

相关文章:

java - 我什么时候应该将所需的库提取/打包到生成的 JAR 中?

java - 您可以使用 JDBC 仅连接到实例而不指定数据库吗?

java - JVM退出代码1073807364的原因是什么?

android - 如何在 Kony 应用程序中执行逻辑,具体取决于它是在 iOS、Android 还是 Web 浏览器上运行

c - Swig 的替代品?

java - 如何在模型- View - Controller 中为模型设计接口(interface)?

c# - 没有实现接口(interface)成员错误

Java HttpUrlConnection.getInputStream() 延迟

java - CustomList<T extends A> 类型不匹配

Android - 显示 mysql 数据库中的前十个条目