【问题标题】:Java: Inheritance of generic Node and TreeJava:通用节点和树的继承
【发布时间】:2014-05-15 04:53:22
【问题描述】:

遇到以下问题: 我正在使用我自己的通用 Tree 类。另一个类,一个联系人列表,继承自该 Tree 类。我这样做的原因是,还有其他类都需要相同的树功能,但它们的用途不同。

Node 也是一个通用节点,也继承了特殊的节点类型,如电话列表、电子邮件联系人列表等。

在 Tree 类中有一些使用局部变量 Node 的方法。在联系人列表树中,我需要将这个变量设为Contact(从 Node 继承)。当我使用联系人列表中的一种方法时,它将根节点定义为Node 而不是Contact,因此它使用通用节点而不是继承的节点。

看起来是这样的:

public class Tree {

  Node root;

  public void insert( String x ) {
        root = insert( x, root );
 }

这是联系人列表(根是 Contact 类型(扩展节点):

public class ContactList extends Tree {

Contact root;

这是Node

public class Node {

String idString;
    Node leftChild;
    Node rightChild;

    public Node() {}

    public Node(String idString) {
        this.idString = idString;
    }

}

我如何告诉继承方法插入不是使用本地root,而是使用继承类中的方法。

我试图在ContactList的构造函数中解决这个问题:

public ContactList() {
super.root = this.root;
}

没用。我认为它会立即被 Tree 类覆盖,那么继承通用节点行为的正确方法是什么?

【问题讨论】:

  • 你应该使用泛型,Node<Contact>

标签: java inheritance


【解决方案1】:

您不需要ContactList 中的根变量。如果ContactNode,您可以在构造函数或超类Tree 的其他方法中轻松分配它:

public class Tree {

  Node root;

  public Tree(Node root) {
    this.root = root; 
  }

  public void insert( String x ) {
        root = insert( x, root );
  }
}

对于ContactList

public class ContactList extends Tree {

  public ContactList(Contact contact) {
    super(contact);
  }
...
}

假设Contact extends Node。现在,当您在 ContactList 实例上调用继承的方法时,将使用 Contact 实例。

ContactList list = new ContactList(new Contact(...));
list.insert("X");

但是如果你想去除Contact和Node之间的继承关系,你应该使用Java Generic

public class Tree<T> {
  T root;

  public void insert(T node) {
    ...
  }
}

然后:

Tree contactTree = new Tree<Contact>();
...
contactTree.insert(Contact c);

【讨论】:

    【解决方案2】:

    使用泛型。修改 Tree 和 Node 以具有以下泛型类型:

    • Tree&lt;T extends Tree&lt;T,N&gt;,N extends Node&lt;T,N&gt;&gt;
    • Node&lt;T extends Node&lt;T,N&gt;,N extends Node&lt;T,N&gt;&gt;

    然后在他们的字段和方法中只使用泛型类型 T 和 N。这使您可以拥有 f.e.子类

    • ContactTree extends Tree&lt;ContactTree,ContactNode&gt;
    • ContactNode extends Node&lt;ContactTree,ContactNode&gt;

    请记住,如果您的 ContactTree 最终没有任何方法或字段,那么简单的 Tree&lt;N extends Node&gt; 就足够了。

    【讨论】:

    • 我尝试了您的解决方案,但它使用以下错误标记 Node:类型 Node 的参数数量不正确;它不能用参数 参数化
    • 是的,忘记添加另一个类型参数,已修复。
    • 现在节点似乎可以工作,但在树中它说:绑定不匹配:类型 T 不是 Node> 的有效替代品T,N>
    • 应该是Node&lt;T extends Tree&lt;T,N&gt;,N extends Node&lt;T,N&gt;&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多