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

China☆狼群 提交于 2019-12-01 01:14:44

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