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?
How about this: