Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to avoid default call to super() in Java?

Assume for some reason that I don't want to implicitly call super() which is done by default.

class Animal {
    public Animal() {
        System.out.println("Constructing an animal.");
    }
}
class Dog extends Animal {
    public Dog() {
        System.out.println("Constructing a dog.");
    }
    public static void main(String[] a) {
        new Dog();
    }
}

Is there any way to "disable" the default behavior that super() is invoked when making a new Dog? Or would that be principally and conceptually wrong?

I mean there could be cases where you would want only the constructor of the subclass and not invoke the construction of the baseclass, and still inherit the baseclass.

like image 644
Niklas Rosencrantz Avatar asked Aug 12 '26 00:08

Niklas Rosencrantz


1 Answers

If I understand you correctly you want to override the behavior of the Animal constructor or just not call it. If so you're conceptually wrong: you always need to call a super constructor, the only thing you could to with the calls is provide a non-default constructor, i.e. one with arguments and provide appropriate arguments to influence the behavior of that constructor (e.g. by either selecting a different constructor, passing some sort of strategy/function object etc.)

Another way might be to provide some init() method that the default constructor is calling and which you can override but there are a few problems with it, e.g.:

  • If the overridden method tries to access anything only visible to the subclass (e.g. additional fields) you could run into problems because those haven't been initialized yet.
  • That method can't initialize any final field.
like image 74
Thomas Avatar answered Aug 13 '26 12:08

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!