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);
}
}
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.
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.
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.
In AS2, you can pass parameters to a super class's constructor using super() .
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
}
}
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With