Abstract Java class, abstract constructor

I am trying to find a way to force the user to implement an interface or extend a class to create multiple constructors. I thought that the way to do this would be to create an abstract constructor in an abstract class, but I realized that I could not do this.

How can I solve this problem? Is there a way to get the user to create a specific constructor?

Thanks!

+5
source share
3 answers

Not. But since constructors are often replaced by factory methods, you can implement abstract factory methods or just other templates, such as the builder template.

+6
source

Not. Not.

However, you can create a unit test framework that uses reflection to ensure you have the right constructors.

+4
source

You cannot create an abstract constructor, but a workaround you can do:

Deploy the abstract class with all the constructors you want to implement. In each of them, you will have one statement that references the abstract method of this class, the implementation of which will be in a subclass. Thus, you force the user to provide the body for the constructor by implementing an abstract method. For instance:

 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 an implementation of these two methods, which can represent the bodies of 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 } } 
+4
source

Source: https://habr.com/ru/post/1210476/


All Articles