[ACCEPTED]-Java: how to initialize child when super constructor requires parameter-inheritance

Accepted answer
Score: 10

Assuming var is private and you need to set the 7 value with the constructor (which seems 6 to be the point of the question, otherwise 5 there are many easy solutions), I would 4 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 3 like that. You have no choice, as explicit 2 constructor invocation must happen on the 1 first line of the wrapping constructor.

Score: 2

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 2 method is the only thing you can do before 1 calling the superclass constructor.

Score: 0

Alternative to hvgotcodes, since it looks 1 like you also want to set A's variable...

class B extends A {
 int var2;

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

Another approach could be to add a protected 4 constructor without parameters to A that 3 relies on lazy initialization:

class A {
    int var;

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

    /**
    * Just use this constructor if you initialize var
    */
    protected A(int x) {
    }
}

class B extends A {
    int var2;

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

But that's 2 hard to document, not very obvious to team 1 members and shouldn't be used for an api.

More Related questions