Prepare parameter for superconstructor

I have a base class that needs to be built with a parameter. In the child class, I need to prepare this parameter before building the base class, but in Java super need to be called before anything else. What is the best way to handle this situation (see a simple example below).

class BaseClass { protected String preparedParam; public BaseClass(String preparedParam) { this.param = param; } } class ChildClass { public ChildClass (Map<String, Object> params) { // need to work with params and prepare param for super constructor super(param); } } 
+6
java super constructor
source share
4 answers

You can create a static method that performs the conversion and calls it.

 class ChildClass { static String preprocessParams(Map<String, Object> params) { ... return someString; } public BaseClass(Map<String, Object> params) { super(preprocessParams(params)); } } 
+11
source share

Here is one approach:

 class ChildClass { public ChildClass(Map<String, Object> params) { super(process(params)); } private static String process(Map<String, Object> params) { // work with params here to prepare param for super constructor } } 
+5
source share

due to the many parameters that need to be prepared / initialized, just the factory method is the best solution for me. In my opinion, this is a slightly clearer solution. Anyway, thanks to everyone for the answers.

 class BaseClass { protected Object preparedParam; public BaseClass(Object preparedParam) { this.preparedParam = preparedParam; } } class ChildClass extends BaseClass { private ChildClass(Object preparedParam) { super(preparedParam); } public static ChildClass createChildClass(Map<String, Object> params) { Object param1 = params.get("param1"); // prepare params here ChildClass result = new ChildClass(param1); // do other stuff return result; } } 
+2
source share

I would rate the Roman answer as the best so far. If the parent class provides a default constructor, you can instantiate the super object and then use the setter method.

0
source share

All Articles