Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept super class constructor argument?

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?

like image 958
aviad Avatar asked Feb 18 '12 22:02

aviad


People also ask

How this () and super () are used with constructors?

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.

Can you use both this () and super () in the same constructor?

“this()” and “super()” cannot be used inside the same constructor, as both cannot be executed at once (both cannot be the first statement).

How do we invoke super class constructor?

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.

Can we place super in a constructor?

The super(... args) expression is valid in class constructors.


1 Answers

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;
}
like image 92
Oliver Charlesworth Avatar answered Oct 02 '22 16:10

Oliver Charlesworth