如何使用自己类型的成员扩展类? [英] How to extend a class with a member of its own type?

查看:87
本文介绍了如何使用自己类型的成员扩展类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们需要使用一个名为BaseNode的类实现不同类型的树,从中派生出其他类型的节点,它假设有一个名为 parent 的实例变量它自己的类型,通常看起来像:

Suppose we need to implement different types of tree with a class called "BaseNode" from which other type of Nodes are derived and it suppose to have an instance variable called parent of its own type, generally it looks like:

class BaseNode{
   //...some fields
   BaseNode parent;
   //...other methods
}

现在如果我要去为更多成员派生AVL树节点:

Now if I am going to derive Node for AVL tree with more members:

class AVLNode extends BaseNode{
    //...other useful stuff

}

原来的父母(& left & right )节点成员仍将是 BaseNode 这阻止我实现AVL树。
任何能告诉我如何解决这个继承问题的人?
谢谢!

the original parent (&left&right)node members will still be type BaseNode which prevents me to implement the AVL tree. Any one who could tell me how we could solve this inheritance problem? Thanks!

推荐答案

解决方案1 ​​ - 任何时候访问 parent ,将其强制转换为(AVLNode)parent 。您可以在 AVLNode 中编写一个访问者,以使其更方便。

Solution 1 - Any time you access parent, cast it to (AVLNode) parent. You could write an accessor in AVLNode to make it more convenient.

class AVLNode extends BaseNode {
    public AVLNode getParent() {
        return (AVLNode) parent;
    }
}

解决方案2 - 制作 BaseNode 将子类作为参数的泛型类。现在 parent 可以是所需的确切类型。

Solution 2 - Make BaseNode a generic class that takes the subclass as a parameter. Now parent can be the exact type needed.

class BaseNode<T extends BaseNode<T>> {
    T parent;
}

class AVLNode extends BaseNode<AVLNode> {
}

这篇关于如何使用自己类型的成员扩展类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆