5

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!

2
  • 1
    What constructors do you want implemented (and why)? Commented Jan 6, 2015 at 14:10
  • An empty constructor and a copy constructor. However I put the question because I want to know for a general purpose. Commented Jan 6, 2015 at 14:13

3 Answers 3

9

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 
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

However the simple factory method proved to be a better idea.
8

No. But, as Constructors are often substituted by factorymethods anyway, you could implement abstract factorymethods or just other patterns like the builderpattern.

Comments

4

No there isn't.

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

1 Comment

Thanks, I'd better implement a method named newInstance in the interface implemented by the class.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.