Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What happens if a call super class first and subclass after?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading