简体   繁体   English

自己类中的对象

[英]An object inside its own class

So let's say: 所以说:

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

public class A {
  A aa = new A();
}
  1. So...when I run it ...it gives : java.lang.StackOverflowError. 所以...当我运行它时...给出了:java.lang.StackOverflowError。 So, my explanation is that object a generation at line 1, furthers creates object aa generation at line 2...and then it enters a recursion .... which keeps creating object after object, until the heap memory is full. 所以,我的解释是,对象a在1号线代,进一步加强将创建对象aa代第2行...然后进入一个递归....它不断创建对象之后的对象,直到堆内存已满。

  2. If the objects are created on Heap...then why does it say StackOverflowError ?? 如果对象是在堆上创建的...那么为什么会说StackOverflowError?

Well, it's using both heap and stack. 好吧,它同时使用了堆栈。 The stack space is because you're in the constructor for A , recursively. 堆栈空间是因为您递归地位于A的构造函数中。 It would be simpler to see this if you put the initialization in the body of the constructor: 如果将初始化放在构造函数的主体中,则将更容易看到以下内容:

public class A {
  A aa;

  public A() {
     aa = new A();
  }
}

So the A constructor calls itself, then calls itself, etc. There's generally rather more heap space available than stack space, hence why you're running out of stack space first. 因此, A构造函数先调用自身,然后调用自身,依此类推。通常,可用的堆空间比堆栈空间要多,因此为什么您首先要耗尽堆栈空间。 If your class had a lot of fields, you would conceivably run out of heap space first - although usually the heap is pretty huge in modern machines. 如果您的类有很多字段,则可以想象首先会用完堆空间-尽管通常在现代计算机中堆非常大。

The reason for a stack overflow is simply that the stack runs out of space before the (small) As can fill up the heap. 堆栈溢出的原因很简单,就是在(小)As可以填满堆之前,堆空间不足。

You have correctly recognized the recursion. 您已经正确识别了递归。 So! 所以!

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

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