0

I don't really use super() anywhere but still the superclass' constructor is called. Why is it so?

class SuperDemo{
    public static void main(String[] args) {
        B subClass = new B();
        subClass.showbiz();
    }
}

class A{
    int i;
    A(){
        i = 10;
    }
}

class B extends A{
    
    void showbiz(){
        System.out.println("i in subclass " + i);
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
KrevoL
  • 103
  • 1
  • 1
  • 7
  • 1
    This is part of the language. If you don't call a `super` explicitly the compiler calls the no-arg version. Always. – Brick Jun 18 '21 at 16:45
  • It's implicit. It must be called. As a convenience, the compiler allows you to not call it explicitly, but it's called whether or not you write it. – Michael Jun 18 '21 at 16:45
  • If you have a subclass of `A`, then instances of that subclass *are* instances of `A`, so they have to be constructed in accordance with `A`'s rules (plus possibly some additional rules imposed by the subclass). It never makes sense to construct an instance of `A` without calling its constructor. If you find yourself in a situation where that makes sense to do, then you shouldn't be using inheritance in that situation. – Silvio Mayolo Jun 18 '21 at 16:52

1 Answers1

1

That's how the language works. If you don't explicitly call the superclass' constructor using super, the default constructor of the superclass will be called implicitly.

Mureinik
  • 297,002
  • 52
  • 306
  • 350