Default constructors in Java

Use the super constructor:

public Bar(int a, double b, ...) {
    super(a, b, ...);
}

So all nice and well, but how do I now get this to work without duplicating this constructor in every deriving class?

You do need to duplicate the constructor signatures - if you want the subclass to have constructors with the same signatures. But you don't need to duplicate the code - you just chain to the superclass constructor:

public Bar(int x, int y) {
    super(x, y);
    // Any subclass-specific code
}

Of course if you can work out the superclass parameters from a different set of parameters, that's fine. For example:

public Bar(int x) {
    super(x, x * 2);
    // Any subclass-specific code
}

You really need to work out what information is required to construct a Bar - that should dictate your constructors.

If this is a problem, it's possible that you're overusing inheritance. It's hard to say for sure without any idea of what your actual classes are, but you should look at using composition instead of inheritance. It's no panacea, but it can avoid this sort of thing.


No, there's no more "sane" approach. If your base class has no default constructor, then you must explicitly call the correct constructor from all the children classes.

Note this doesn't mean children classes need to have the exact same constructor than base class. For example this is perfectly valid:

class Foo {

    protected int a;
    protected int b;

    protected Foo(final int a, final int b) {
        this.a = a;
        this.b = b;
    }
}

class Bar extends Foo {

    protected Bar() {
        super(0,0);
    }
}