简体   繁体   English

Java中的对象初始化

[英]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. 它生成java.lang.StackOverflowError异常。 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. 这也会生成相同的java.lang.StackOverflowError异常。 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. 你经历了一个循环,在这个循环中,构造函数将它自己调用为servaral次,直到它溢出为止。

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 . 在这两种情况下,只有一次区别是你提供了一个带有print语句的默认no org构造函数,这样你就可以看到print语句,直到你收到错误

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... 每次创建Skyler实例时,都会初始化该实例的s1成员,这将创建另一个Skyler实例,该实例初始化该另一个实例的s1成员,从而创建另一个Skyler实例,依此类推......

In other words, you have an infinite chain of calls to the Skyler constructor, which causes StackOverflowErr . 换句话说,您对Skyler构造函数有一个无限的调用链,这会导致StackOverflowErr

Delete Skyler s1=new Skyler(); 删除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. 。使用你的代码,Skyler类有一个类型为Skyler的变量,然后它会一次又一次地创建一个Skyler,所以存在StackOverflowException

Check the logic, you create a new Skyler , what does this do? 检查逻辑,你创建一个新的Skyler ,这有什么作用? It creates a new Skyler , surprisingly this new Skyler creates another new Skyler . 它创造了一个新的Skyler ,令人惊讶的是这个新的Skyler创造了另一个新的Skyler This all comes from your line Skyler s1=new Skyler(); 这一切都来自你的线Skyler s1=new Skyler(); (the one that is not static), which recursivly creates endles instances of the Object Skyler . (非静态的那个),它递归地创建了Object Skyler endles实例。

The class Skyler calls its own constructor. Skyler类调用自己的构造函数。 So while creating an instance of Skyler, another instance of Skyler is created and so on... the result is a StackOverflow. 因此,在创建Skyler的实例时,会创建另一个Skyler实例,依此类推......结果是StackOverflow。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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