[英]StackOverflowError when making a subclass
My superclass: 我的超类:
public class Node {
public MyPoint myPoint = new MyPoint();
}
My empty subclass: 我的空子类:
public class MyPoint extends Node {
}
The question below was the closest to the problem I could find, however my subclass, in this case, is empty and has no constructors. 以下问题是我所能找到的最接近的问题,但是在这种情况下,我的子类为空并且没有构造函数。
Calling a subclass constructor from a superclass 从超类调用子类构造函数
I get the following error: 我收到以下错误:
Exception in thread "JavaFX Application Thread" java.lang.StackOverflowError
...
at engine.MyPoint.<init>(MyPoint.java:3)
at engine.Node.<init>(Node.java:28)
at engine.MyPoint.<init>(MyPoint.java:3)
at engine.Node.<init>(Node.java:28)
at engine.MyPoint.<init>(MyPoint.java:3)
at engine.Node.<init>(Node.java:28)
...
I don't understand why and how there is no recursion as I see it. 我不明白为什么以及为什么看不到递归。 How is this 这怎么样
public MyPoint myPoint = new MyPoint();
Different than this (for example in JavaFX), while creating a new Group doesn't give me the error? 与此不同(例如,在JavaFX中),但是创建新组时不会出现错误?
public Group group = new Group();
MyPoint
extends Node
, so when you create an instance of MyPoint
, you'll first have to initialize its parent Node
. MyPoint
扩展了Node
,因此,当您创建MyPoint
的实例时,首先必须初始化其父Node
。 This means initializing the myPiont
member and so on until you get a StackOverflowError
. 这意味着初始化myPiont
成员,依此类推,直到得到StackOverflowError
为止。
There isn't enough context here to suggest changes, but you should probably lose this member. 这里没有足够的上下文来建议更改,但是您可能应该失去此成员。
If your Node class absolutely needs a MyPoint field, you have a few options: 如果您的Node类绝对需要MyPoint字段,则有以下几种选择:
public class Node {
public MyPoint myPoint = new MyPoint();
}
to this: 对此:
public class Node {
public MyPoint myPoint; // note that MyPoint NOT created here
public Node(MyPoint myPoint) {
this.myPoint = myPoint; // but rather passed in HERE
}
}
This way you don't recursively create Node objects each time a Node is created, but rather separate the creation of MyPoint instances from Node instances. 这样,您不必在每次创建Node时都递归地创建Node对象,而是将MyPoint实例的创建与Node实例分开。 Alternatively, this can be also be solved using a setter method. 可替代地,这也可以使用设置方法来解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.