Java 强制要求扩展类

24
在Java中,我能否强制要求继承抽象类的类实现一个带有Object类型参数的构造函数?
类似于
```java public abstract class MyClass { public MyClass(Object object) { // constructor implementation } } ```
public abstract class Points {

    //add some abstract method to force constructor to have object.
}

public class ExtendPoints extends Points {

    /**
     * I want the abstract class to force this implementation to have
     *  a constructor with an object in it?
     * @param o
     */
    public ExtendPoints(Object o){

    }
}
6个回答

29

您可以在抽象类中使用带参数的构造函数(如果想要禁止匿名子类,则将其设置为受保护的)。

public abstract class Points{
    protected Points(Something parameter){
        // do something with parameter
    }
}

这样做会强制实现类拥有一个显式构造函数,因为它必须使用一个参数调用超类的构造函数。

然而,你无法强制重写类具有带参数的构造函数。它总是可以像这样伪造参数:

public class ExtendPoints extends Points{
    public ExtendPoints(){
        super(something);
    }
}

5
正如其他人所说,构造函数的签名无法强制执行,但是您可以使用AbstractFactory模式来强制执行特定的参数集。然后,您可以将工厂接口的create方法定义为具有特定签名。

2

构造函数不会被继承,因此每个类都需要提供自己的构造函数,除非您没有指定构造函数并且获得默认的无参数构造函数。


2

也许在编译时不可能,但是您可以使用反射来在运行时检查是否声明了所需的构造函数:

public abstract class Points {

    protected Points() {
        try {

            Constructor<? extends Points> constructor = 
                getClass().getDeclaredConstructor(Object.class);
            if (!Modifier.isPublic(constructor.getModifiers()))
                throw new NoSuchMethodError("constructor not public");

        } catch (SecurityException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchMethodException ex) {
            throw (NoSuchMethodError) new NoSuchMethodError().initCause(ex);
        }
    }
}

0
如果您在Points类中添加一个public Points(Object o) {}构造函数,您将强制任何子类构造函数调用该超级构造函数。但是,我认为没有办法确保子类使用完全相同的构造函数签名。

-1

编辑

好的,不,无法强制实现带参数的构造函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接