Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepare parameter for super constructor

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 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);
    }
}
like image 363
michal.kreuzman Avatar asked Mar 22 '11 09:03

michal.kreuzman


People also ask

How do you pass parameters to a constructor?

Arguments are passed by value. When invoked, a method or a constructor receives the value of the variable passed in. When the argument is of primitive type, "pass by value" means that the method cannot change its value.

How do you call a parameterized constructor using super?

Example 5: Call Parameterized Constructor Using super() The compiler can automatically call the no-arg constructor. However, it cannot call parameterized constructors. If a parameterized constructor has to be called, we need to explicitly define it in the subclass constructor.

Can we pass parameter in super?

Starting from Dart 2.17, you can pass constructor parameters to the superclass with a new shorthand syntax. In other words, you had to call super explicitly in order to pass arguments to the parent constructor.

How do you forward an argument to a super class constructor?

In AS2, you can pass parameters to a super class's constructor using super() .


2 Answers

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
    }
}
like image 22
WhiteFang34 Avatar answered Oct 27 '22 20:10

WhiteFang34


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));
    }
}
like image 125
Roman Avatar answered Oct 27 '22 19:10

Roman