gpt4 book ai didi

java - OOP 使用子类的实例初始化实例变量

转载 作者:行者123 更新时间:2023-12-01 14:50:50 25 4
gpt4 key购买 nike

我正在尝试在我的类Node上实现空对象设计模式:

    class Node{
Node nextNode;
char key;
Node prevNode;

/*
Would like to initialize nextNode and prevNode to instance of
NullNode, something like this (I know what I am doing is wrong)
*/
Node() {
nextNode = new NullNode();
prevNode = new NullNode();
}
}

class NullNode extends Node {
....
}

使用此代码,我收到 StackOverflowError 异常。我该如何解决这个问题?

最佳答案

您将得到一个StackOverflow,因为父构造函数始终被调用(另请参阅: https://stackoverflow.com/a/527069/664108 )。在您的情况下,这会导致无限递归。

为了避免这种情况,您必须在 Node 构造函数中添加检查,并从 NullNode 构造函数显式调用它:

public class Node
{
Node nextNode;
char key;
Node prevNode;

Node() {
Node(true);
}
Node(boolean createNullNodes) {
if (createNullNodes) {
nextNode = new NullNode();
prevNode = new NullNode();
}
}
}

public class NullNode extends Node
{
NullNode() {
super(false);
}
}

对于 NullObject 模式,更好的解决方案是使用接口(interface)。这消除了构造函数问题,并且还允许从 NullNode 中删除不需要的 nextNodeprevNode 变量。

界面示例:

public interface INode
{
public char getKey();
public INode getNext();
public INode getPrev();
// ...
}

public class Node implements INode
{
Node nextNode;
char key;
Node prevNode;

Node() {
nextNode = new NullNode();
prevNode = new NullNode();
}
public char getKey() {
return key;
}
public INode getNext() {
return nextNode;
}
public INode getPrev() {
return prevNode;
}
}

public class NullNode implements INode
{
public char getKey() {
return null;
}
public INode getNext() {
return this;
}
public INode getPrev() {
return this;
}
}

关于java - OOP 使用子类的实例初始化实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14873057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com