Java constructor inheritance?

I always thought that constructors are not inherited, but look at this code:

class Parent {
    Parent() {
        System.out.println("S1");
    }
}

class Child extends Parent {
    Child() {
        System.out.println("S2");
    }
}

public class Test5 {
    public static void main(String[] args) {
        Child child = new Child();
    }
}

//RESULT:
//S1
//S2

This shows that Child inherited the constructor. Why is S1 on the result? Is it possible to create 2 constructors without parameters and have only a child constructor for the result without a base constructor (only S2)?

+6
source share
6 answers

Everything that you see here is called a constructor chain. Now what is a chain of constructors:

The constructor chain is inherited. Subclassing the first constructor method is to call its constructor the superclass method. This ensures that the creation of the subclass object begins with the initialization of the classes above it in the chain inheritance.

. , . , . . ()

. , Child javac:

class Child extends Parent 
{ 
  Child()
  {
    super();//automatically inserted here in .class file of Child
    System.out.println("S2");
  }
}

:

Parent() 
{
    super();//Constructor of Object class
    System.out.println("S1");
}

:

S1 //output from constructor of super class Parent
S2 //output from constructor of child Class Child
+16

Java :

(, ) . , , .

, .

- , super().

+2

.

.

2 Child .

, . Java . , .

public SuperClass() {
   ...
}

public DerivedClass() {
  //Compiler here call no argument constructor of Super class.
}
+1

:

, .

. , Child . Parent. . Child, Object, , Child.

:

S1
S2
0

, . Java:

Object, "super();", , .

0

, . . , .

0

All Articles