java强制扩展类

Mar*_*hin 21 java constructor abstract-class

在Java中,我可以以某种方式强制扩展抽象类的类来实现其构造函数,并将Object作为参数吗?

就像是

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){

    }
}
Run Code Online (Sandbox Code Playgroud)

Sea*_*oyd 27

您可以在抽象类中使用带有参数的构造函数(如果要禁用匿名子类,请将其保护).

public abstract class Points{
    protected Points(Something parameter){
        // do something with parameter
    }
}
Run Code Online (Sandbox Code Playgroud)

这样做,您强制实现类具有显式构造函数,因为它必须使用一个参数调用超级构造函数.

但是,您不能强制覆盖类具有带参数的构造函数.它总是可以伪造这样的参数:

public class ExtendPoints extends Points{
    public ExtendPoints(){
        super(something);
    }
}
Run Code Online (Sandbox Code Playgroud)


Ber*_*ase 5

正如其他人之前所说的那样,构造函数的签名不会被强制执行,但您可以通过使用AbstractFactory模式来强制执行一组特定的参数.然后,您可以定义工厂界面的create方法以具有特定签名.