开发者

Prepare parameter for super constructor

开发者 https://www.devze.com 2023-02-19 09:30 出处:网络
I have a base class that have to be constructed with parameter. In child class I need to prepare this parameter before constructing base class but in Java super must be called before anything else. Wh

I have a base class that have to be constructed with parameter. In child class I need to prepare this parameter before constructing base class but in Java super must be called before anything else. What's开发者_Go百科 the best way to handle this situation (see 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);
    }
}


You can create an static method, that does the transformation and call that.

class ChildClass {

    static String preprocessParams(Map<String, Object> params) {
        ...
        return someString;
    }

    public BaseClass(Map<String, Object> params) {
        super(preprocessParams(params));
    }
}


Here's 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
    }
}


because of many parameters that have to be prepared/initialized is simple factory method better solution for me. It's little bit clearer solution at my point of view. Anyway thanks all for 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;
  }
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消