I was asked the following question during phone interview I had:
Given the following class definition:
public class ClassA {
public ClassA(int x) {
// do some calculationand initialize the state
}
}
and its child class that initializes a super class using a random integer generator.
public class ClassB extends ClassA {
public ClassB() {
super(StaticUtilityClass.someRandomIntegerValGenerator())
}
}
you need to intercept the value of x (the random int produced by someRandomIntegerValGenerator) and store it in ClassB member. ClassA can not be changed. I ended up with no idea how this can be done because the first call inside the ClassB constructor needs to be the call to super(). Untill the super() was called there is no state for ClassB and the value produced by the someRandomIntegerValGenerator can not be assigned to no ClassB member. The only direction I had was using a ThreadLocal but I think it should be some easier solution.
Any thoughts?
super() acts as immediate parent class constructor and should be first line in child class constructor. this() acts as current class constructor and can be used in parametrized constructors. When invoking a superclass version of an overridden method the super keyword is used.
“this()” and “super()” cannot be used inside the same constructor, as both cannot be executed at once (both cannot be the first statement).
To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword. super() can be used only inside the subclass constructor and must be the first statement.
The super(... args) expression is valid in class constructors.
How about this:
public class ClassB extends ClassA {
public ClassB() {
this(StaticUtilityClass.someRandomIntegerValGenerator());
}
private ClassB(int x) {
super(x);
// Can access x here, e.g.:
this.x = x;
}
private int x;
}
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