简体   繁体   中英

StackOverFlow Error in Instantiating an Object

I'm reviewing for a certification exam and I experimented with the following codes:

class A {   
    B b = new B();
    static {
        System.out.println("A static.");
    }
    {
        System.out.println("A instance.");
    }
    A() {
        System.out.println("A constructor.");
    }
}
class B extends A {
    static {
        System.out.println("B static.");
    }
    {
        System.out.println("B instance.");
    }
    B() {
        System.out.println("B constructor.");
    }
}

public class Raaawrrr {
    public static void main(String args[]) {
        A a = new A();
    }
}

It prints:

A static. B static.

and causes a stack overflow afterwards. I'm having a hard time understanding why. Would you be able to help me out?

A instantiates B. B happens to also be of type A, so that gets instantiated again. Which instantiates B... and so forth.

You are creating an object of class B which is sub-class of A in class A . Note that the constructor of super-classes must be executed before the execution of sub-class constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM