How to extend a class with a member of its own type?

自闭症网瘾萝莉.ら 提交于 2019-12-03 22:51:59

问题


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
}

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

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

}

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:


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;
    }
}

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> {
}


来源:https://stackoverflow.com/questions/50053642/how-to-extend-a-class-with-a-member-of-its-own-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!