Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 695
amor214 Avatar asked Jul 28 '26 13:07

amor214


2 Answers

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

like image 121
Esteban Araya Avatar answered Jul 31 '26 04:07

Esteban Araya


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.

like image 43
KV Prajapati Avatar answered Jul 31 '26 04:07

KV Prajapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!