【发布时间】:2014-12-22 11:11:54
【问题描述】:
我明白为什么下面的代码不起作用。这是因为卷积将调用 Base,而不是 Derived。这段代码非常简单,并且具有自引用。我扩展了“自引用类”,但我遇到了这个问题。
class Base
{
public int important_data;
protected Base child;
public int sum()
{
if(child != null)
{
return important_data + child.sum();
}
else
{
return important_data;
}
}
}
class Derived extends Base
{
public int more_important;
public int convolusion()
{
if(child != null)
{
return more_important*important_data + child.convolusion();
}
else
{
return more_important*important_data;
}
}
}
那么,有什么方法可以做到吗?
【问题讨论】:
-
在调用 convolusion 时如何确定子节点是 Derived 类型?
-
child不知道convolusion()方法。 -
@Braj 实际上我正在使用带有自引用类的 Tree。我想使用某种 DFS 进行一些迭代,并且我想扩展原始 Tree 类。而且,有一个 null 的哨兵,所以当没有孩子时它会停止。
-
在
Base类中创建一个空或抽象方法public int convolusion()并在Derived类中覆盖。 -
@X.L.Ant 这就是重点。我不能确定那是“派生的”。所以我想知道另一种方式。我当然不能覆盖字段。
标签: java inheritance design-patterns field self-reference