为什么我会在这里收到 StackOverflowError?
为什么这段java代码会产生StackOverflowError
?我知道这在某种程度上与递归泛型类型参数有关。但我不太清楚整个机制。
public class SomeClass<T extends SomeClass> {
SomeClass() {
new SomeClassKiller();
}
private class SomeClassKiller extends SomeClass<T> {
}
public static void main(String[] args) {
new SomeClass();
}
}
Why does this java code produce StackOverflowError
? I understand that this somehow connected with recursive generic type parameter. But I don't understand clear the whole mechanism.
public class SomeClass<T extends SomeClass> {
SomeClass() {
new SomeClassKiller();
}
private class SomeClassKiller extends SomeClass<T> {
}
public static void main(String[] args) {
new SomeClass();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
通用部分并不重要——类的嵌套也并不重要。看看这对几乎等价的类,它应该更明显:
所以子类构造函数调用超类构造函数 - 然后创建一个新的子类,它调用超类构造函数,它创建一个新的子类,等等...... !
The generic part doesn't matter - nor does it really matter that the class is nested. Look at this mostly-equivalent pair of classes and it should be more obvious:
So the subclass constructor calls the superclass constructor - which then creates a new subclass, which calls into the superclass constructor, which creates a new subclass, etc... bang!
这里它从另一个构造函数调用一个构造函数,并从中调用前一个构造函数,循环构造函数链,请参阅下面的注释
Here it is invoking one constructor from another and from it the previous one, cyclic constructor chain, see the comments below
这是因为类 SomeClass 和类之间发生了递归构造函数调用
某类杀手。
This is because of the Recursive constructor calls happening between the classes SomeClass and
SomeClassKiller.
编译器生成的代码是这样的,所以当你创建一个对象时,它会永远递归地调用 SomeClass 和 SomeClassKiller 。
The code produced by the compiler is something like this, so when u create an object it recursivly calls the SomeClass and SomeClassKiller for ever.
构造函数是从上到下调用的,也就是说,如果类
A
派生自B
,A 的构造函数将首先调用父构造函数 (B
)。在你的例子中,
new SomeClassKiller()
递归地调用SomeClass
的构造函数,而该构造函数又构造了另一个SomeClassKiller
……就是这样。Constructors are invoked top-to-bottom, that is if a class
A
derives fromB
, A's constructors will first invoke the parent constructor (B
).In you case,
new SomeClassKiller()
recursively calls the constructor ofSomeClass
which in turn constructs anotherSomeClassKiller
… there it is.main()
方法正在创建SomeClass
的新实例,该实例调用创建新实例的SomeClass
构造函数默认情况下,SomeClassKiller
调用父构造函数并发生堆栈溢出。避免堆栈溢出。将代码更改为如下所示:
The
main()
method is creating a new instance ofSomeClass
which calls theSomeClass
constructor that creates a new instance ofSomeClassKiller
that by default calls the parent constructor and the stackoverflow occurs.To avoid the stackoverflow. Change the code to look as follows: