Home > Software design >  What happens if a call super class first and subclass after?
What happens if a call super class first and subclass after?

Time:02-28

class A{
    public A(){ System.out.println("A constructor"); }
    static { System.out.println("A static init block"); }}

class B extends A{
    public B(){ System.out.println("B constructor"); }
    static { System.out.println("B static init block"); }}

public class Test {

    public static void main(String[] args) {

        A a = new A();
        B b = new B();

    }

}





Selected Answer:    
A static init block

A constructor

B static init block

A constructor

B constructor

The first part is clear that Superclass will be executed first. How about " B b = new B(); " part ? will this subclass go to superclass? if so, why "A static init block" is not printed second time? If a subclass does not go to superclass, why "A constructor" is printed?

Thank you in advance!

CodePudding user response:

The static init block is executed once after the class was loaded. As the class A was loaded when you instantiated A, it no longer needs to be loaded when you instantiate B. Therefore the static initializer is not run again.

The constructor is run every time you create an instance of that class. As the instance is not only an instance of it's direct class but also an instance of the superclass, the superclass constructor is called implicitly if you do not do it explicitly in the subclass constructor. Therefore also the superclass constructor is run every time you instantiate a class.

  • Related