简体   繁体   中英

Java abstract class, abstract constructor

I'm trying to find a way to force the user that will implement an interface or will extend a class to create several constructors. I thought that a way to do that would be to create an abstract constructor in an abstract class, but I figured out that I can't do that.

How can I solve this issue? Is there some method to force the user to create a specific constructor?

Thanks!

不可以。但是,由于构造函数经常被工厂方法替代,您可以实现抽象工厂方法或其他模式,如builderpattern。

You can't create an abstract constructor, but here's a workaround that you can do:

Implement an abstract class with all the constructors you want the user to implement. In each of them, you will have a single statement that refers to an abstract method from this class, which implementations will be in the subclass. This way you will force the user to provide a body for the constructor, via the abstract method implementation. For example:

public abstract class MyAbstractClass {
    public MyAbstractClass(int param) {
        method1(param);
    }

    public MyAbstractClass(int param, int anotherParam) {
        method2(param, anotherParam);
    }

    protected abstract void method1(int param);

    protected abstract void method2(int param, int anotherParam);
}

In the implementation, you will be forced to provide implementation of these two methods, which can represent the bodies of the two constructors:

public class MyClass extends MyAbstractClass {
    public MyClass(int param) {
        super(param);
    }

    public MyClass(int param, int anotherParam) {
        super(param, anotherParam);
    }

    public void method1(int param) {
        //do something with the parameter
    }

    public void method2(int param, int anotherParam) {
        //do something with the parameters 
    }
}

No there isn't.

However you could build a unit test framework that exploits reflection to ensure that the correct constructors are present.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM