简体   繁体   中英

Object initialization in Java

Consider following code.

public class Skyler {
Skyler s1=new Skyler();
public static void main(String asd[]){
         Skyler s2=new Skyler();
    }
}

It generates java.lang.StackOverflowError Exception. Why?

Consider following code also.

public class Skyler {
    Skyler s1=new Skyler();
    static Skyler s2=new Skyler();
    Skyler(){
        System.out.println("const");
    }
    public static void main(String sdp[]){}
}

This is also generating same java.lang.StackOverflowError exception. Why?

Is reason same for both Exceptions?

You are undergone a loop where the constructor calling it self for servaral times until it's overflowed.

For ex :

在此输入图像描述

And the reason is same in both cases. It's calling it self endlessly.

In your both cases there is only once difference that you provided a default no org constructor with a print statement so that you can see that print statement until you got the error .

Each time you create an instance of Skyler , the s1 member of that instance is initialized, which creates another instance of Skyler , which initializes the s1 member of that other instance, which creates another instance of Skyler and so on...

In other words, you have an infinite chain of calls to the Skyler constructor, which causes StackOverflowErr .

Delete Skyler s1=new Skyler(); .With your code,Skyler class has a variable whose type is Skyler,then it will be create a Skyler again and again,so StackOverflowException exists.

Check the logic, you create a new Skyler , what does this do? It creates a new Skyler , surprisingly this new Skyler creates another new Skyler . This all comes from your line Skyler s1=new Skyler(); (the one that is not static), which recursivly creates endles instances of the Object Skyler .

The class Skyler calls its own constructor. So while creating an instance of Skyler, another instance of Skyler is created and so on... the result is a StackOverflow.

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