Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How should i solve a problem with needing to call this() and super() at the same time?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading