Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: how to initialize child when super constructor requires parameter

I have

class A {

    int var;
    public A(int x) {
        var = x;
    }
}


class B extends A {
     int var2;

     public B(int x, int y) {
         super(...);
         var2 = y;
         x = f(y);
     }
 }

For the subclass B, I need to calculate the value x that is used in the constructor of A. If I were free to move super below my x=f(y) then I could pass in the result to the constructor of A (super). But super has to be the first line in the constructor of B.

Is there any way to initialize A with the proper value the first time? What if A.var were final and i couldn't go back and change it after construction?

Sure, I could put super(f(y)), but I could imagine cases where this would become difficult.

like image 604
darKoram Avatar asked Aug 02 '12 22:08

darKoram


2 Answers

Assuming var is private and you need to set the value with the constructor (which seems to be the point of the question, otherwise there are many easy solutions), I would just do it with a static factory-like method.

class B extends A {
     int var2;

     public static B createB(int x, int y) {
         x = f(y);
         return new B(x, y);
     }

     public B(x, y) {
         super(x);
         this.var2 = y;
     }
 }

something like that. You have no choice, as explicit constructor invocation must happen on the first line of the wrapping constructor.

like image 85
hvgotcodes Avatar answered Nov 02 '22 05:11

hvgotcodes


You can do it like this :

class B extends A {
    int var2;

    public B(int x, int y) {
        super(calculateX(y));
        var2 = y;
    }

    private static int calculateX(int y) {
        return y;
    }
}

Calling a static method is the only thing you can do before calling the superclass constructor.

like image 22
Olivier Croisier Avatar answered Nov 02 '22 05:11

Olivier Croisier