1

Okay, so, I have a kind of specific problem. I have a class structure similar to this (simplified for simplicity purposes).

class A {
    A() {
        // long initialization
    }

    A(int someValue) {
        this();
        // do something with someValue
    }
}

class B extends A {
    B() {
        super();
        // some long initialization
    }

    B(int someValue) {
        // What should i do here ?
    }
}

But now, i want to be able to construct class B using the second constructor. But the second constructor should call the super(someValue) constructor to make use of the someValue parameter, but at the same time it needs to call this() to to not have to duplicate the initialization of this class. The problem is that i can't call this and super constructors at the same time.

Also I can't extract the initialization in first constructor to some method, because I have some final fields that needs to be initialized inside the constructor to stay final.

Dipo
  • 23
  • 5

1 Answers1

4

The usual solution is to flip the dependencies between your constructor: call super(someValue) inside B(int someValue), and call this(DEFAULT) inside B(). However, you’ll need to figure out a valid DEFAULT for this case — that is, a default value for someValue that can be used by the parameter-less B() constructor (null often works).

If A() and A(int someValue) do fundamentally different things this won’t work, but that’s a sign that the class A is probably poorly designed (in other words: it should be feasible).

As an alternative, just have both B() and B(int someValue) call a method that performs the rest of the initialisation, after calling super()/super(someValue).

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214