amor214
amor214

Reputation: 201

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?

Upvotes: 2

Views: 84

Answers (2)

KV Prajapati
KV Prajapati

Reputation: 94645

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.

Upvotes: 4

Esteban Araya
Esteban Araya

Reputation: 29664

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

Upvotes: 10

Related Questions