-1

I am studying multilevel inheritance in java and stuck at this concept : that in a class hierarchy , constructors are called in order of derivation, from superclass to subclass. I tried looking for the proper explanation on google but nothing satisfactory.

Please explain with example, it would really be helpful

Kafka2701
  • 25
  • 7
  • This is something you could test easily for yourself. At a guess, I think it's starting with `Object` and moving down the hierarchy, but I didn't try it. – markspace Mar 06 '21 at 19:53
  • `I tried looking for the proper explanation on google but nothing satisfactory`.Well you might find useful reading [JLS](https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.8.7) – rkosegi Mar 06 '21 at 20:04

1 Answers1

-1

I guess it's pretty obvious when you make it explicit:

class A {
  A() {
    System.out.println("3");
  }
}

class B extends A {
  B(String foo) {
    super();
    System.out.println("2" + foo);
  }
}

class C extends B {
  C(String foo) {
    super(foo);
    System.out.println("1");
  }
}

When using these explicit constructor calls, you can see that super(...) is always the first instruction. Though this is what happens:

  1. new C("foo"); will call the C constructor
  2. first line in C constructor will call super constructor (B)
  3. B constructor is called
  4. first line in B constructor will call super constructor (A)
  5. A constructor is called (prints 3)
  6. when all lines of A constructor are done, it will return control to B constructor
  7. B constructor will execute all lines after the super call (prints 2 + foo)
  8. then it will return control to C constructor
  9. C constructor will execute all lines after the super call (prints 1)

When you don't create an explicit constructor this code will still be run in exactly the same order.

It's basically the same as calling methods from within methods, or calling super methods. The only difference is, that you must call the super constructor before you execute any other code.

Benjamin M
  • 23,599
  • 32
  • 121
  • 201