0

I didn't use super() in my subclass constructer(Dog) to call the superclass constructor(Animal) but why did the compiler show the output as "Animal constructor". I just want to know why run Animal constructer without using super() keyword

class Animal{
        Animal(){
            System.out.println("Animal constructor");
        }
    }
    class Dog extends Animal{
        Dog(){
    
            System.out.println("dog constructor");
        }
    }
    public class Main{
        public static void main(String[] args) {
            Dog d = new Dog();
    
        }
    }
  • From the docs: `Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.` – Nico Van Belle May 06 '22 at 06:40
  • Does this answer your question? [Why do this() and super() have to be the first statement in a constructor?](https://stackoverflow.com/questions/1168345/why-do-this-and-super-have-to-be-the-first-statement-in-a-constructor) – B. Johansson May 06 '22 at 06:41

1 Answers1

0

This a basic Java knowledge, the order of initialization of an instance of a class.

If there is a superclass Y of X, then initialize the instance of Y first.

The initialization If the first statement of the X constructor is not a call to this() or super(), then the compiler will insert a no-argument super() as the first statement of the constructor.

Constructors are executed from the bottom up, but since the first line of every constructor is a call to another constructor, the flow actually ends up with the parent constructor executed before the child constructor.

Here X is Dog and Y is Animal

HienNg
  • 51
  • 3