Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java abstract class, abstract constructor

Tags:

java

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!

like image 596
yonutix Avatar asked Dec 01 '22 15:12

yonutix


2 Answers

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 
    }
}
like image 170
Konstantin Yovkov Avatar answered Dec 16 '22 18:12

Konstantin Yovkov


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

like image 30
user2504380 Avatar answered Dec 16 '22 18:12

user2504380