简体   繁体   English

如何用自己的类型的成员扩展类?

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

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: 假设我们需要使用一个称为“ BaseNode”的类来实现不同类型的树,从该类派生其他类型的Node,并且它假设有一个实例变量,该实例变量称为其自身类型的parent ,通常看起来像这样:

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

Now if I am going to derive Node for AVL tree with more members: 现在,如果我要为具有更多成员的AVL树派生Node:

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. parentleftright )节点成员仍将型BaseNode我实现AVL树防止。 Any one who could tell me how we could solve this inheritance problem? 谁能告诉我如何解决这一继承问题? Thanks! 谢谢!

Solution 1 - Any time you access parent , cast it to (AVLNode) parent . 解决方案1- (AVLNode) parent访问parent ,都将其(AVLNode) parent(AVLNode) parent You could write an accessor in AVLNode to make it more convenient. 您可以在AVLNode编写访问AVLNode以使其更加方便。

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

Solution 2 - Make BaseNode a generic class that takes the subclass as a parameter. 解决方案2-使BaseNode成为将子类作为参数的通用类。 Now parent can be the exact type needed. 现在, parent可以是所需的确切类型。

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

class AVLNode extends BaseNode<AVLNode> {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 一个类怎么会有自己类型的成员,这不是无限递归吗? - How can a class have a member of its own type, isn't this infinite recursion? “检测到循环:类型b无法扩展/实现自身或其自身成员类型之一”错误 - “Cycle detected: the type b cannot extend/implement itself or one of its own member types” error 在自己的类中实例化类型 - Instantiating a type in its own class 如何序列化一个可以作为其自身类型参数的泛型 class? - How to serialize a generic class that can be its own type parameter? 数据存储-具有自己类型的Java类 - Datastore - Java class having its own type 一个类可以拥有自己类型的字段吗? - Is it okay for a class to have a field of its own type 如何创建具有类型参数的泛型类的实例,该类在其自己的类中扩展了静态类? - How to create an instance of a generic class that has a type paramater which extends a static class within its own class? 如何在Nashhorn JavaScript中扩展Java类并添加类成员变量 - How to extend Java class in Nashhorn JavaScript and add class member variables java 编译器如何允许 class 拥有自己的类型引用? - How does java compiler allow a class to have its own type reference? 一个类如何访问自己的类名? - How can a class access its own classname?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM