【问题标题】:Java Self Reference with Inhertiance带有继承的 Java 自引用
【发布时间】: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


【解决方案1】:

或者,您可以使用通用基类:

class Base<T extends Base> {
    private T child;
    private int importantData;

    Base(T child) {
        this.child = child;
    }

    Base() {
        this(null);
    }

    public int sum() {
        if (child != null && child != this) {
            return importantData + child.sum();
        } else {
            return importantData;
        }
    }

    protected T child() {
        return child;
    }

    protected int importantData() {
        return importantData;
    }
}

class Derived extends Base<Derived> {
    private int moreImportant;

    public int convolusion() {
        if (child() != null && child() != this) {
            return moreImportant * importantData() + child().convolusion();
        } else {
            return moreImportant * importantData();
        }
    }
}

这样您可以获得类型安全处理,不需要强制转换。

【讨论】:

  • 安全性真的很有意义(特别是!=这个)!但是,因为我不知道泛型类,所以我应该更多地研究它。
【解决方案2】:

您没有显示在哪里初始化 child 成员。为了调用child.convolusion(),您必须确保child 的类型为Derived,并将其转换为Derived

public int convolusion()
{
    if(child != null && child instanceof Derived)
    {
        Derived d = (Derived) child;
        return more_important*important_data + d.convolusion();
    }
    else
    {
        return more_important*important_data;
    }
}

【讨论】:

    【解决方案3】:

    您可以确保孩子的类型,尝试类似:

    if(child != null && child instanceof Derived)
    {
        return more_important * important_data + ((Derived)child).convolusion();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-25
      • 2021-09-24
      • 1970-01-01
      • 2014-08-15
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多