What was done first, parent or child constructor?

I put this code in the compiler

package com.employer.constractor;

public class ConstractorDemo extends A{
    public ConstractorDemo(){
        System.out.print("Demo");
    }
    public static void main(String[] args){
        new ConstractorDemo();
    }
}

class A {
    A(){
        System.out.print("A");
    }
}

And that gave "ADemo" why? I would appreciate a detailed answer to this case and mention how the compiler will deal with this

+4
source share
5 answers

The constructor of the base class (the class Ain your case) is always executed before the constructor of the class you create (the class ConstractorDemoin your case). Therefore Aprinted before Demo.

This constructor:

public ConstractorDemo(){
    System.out.print("Demo");
}

is equivalent to:

public ConstractorDemo(){
    super (); // prints A
    System.out.print("Demo"); // prints Demo
}
+2
source

, , Object.

, Child. , ( n- , Object) ( ). , . . , Object, Parent.

Thumb

  • - - ( (args)), .
  • - , (()).
+2

. super. , . -

+2

Constructor. super. , A Demo .

0

, , - super(); ,
(); , , A(), ConstractorDemo()
: https://www.javatpoint.com/super-keyword

super(); , !

:

public ConstractorDemo()
{  
   super(); // u didn't specified this but compiler will automatically add it  
   System.out.print("Demo");  
} 
0

Source: https://habr.com/ru/post/1621938/


All Articles