![](/img/trans.png)
[英]How to create an instance of a class nested within Static class which is in turn nested within Non-Static class?
[英]How to create an instance of a generic class that has a type paramater which extends a static class within its own class?
因此,我有一个通用类BinaryTree
用作源代码,它具有一个称为Node
的类型参数(通常将其称为T
)。 该类如下所示:
public class BinaryTree<Node extends BinaryTree.BTNode<Node>> {
public static class BTNode<Node extends BTNode<Node>> {
public Node left;
public Node right;
public Node parent;
}
public BinaryTree(Node sampleNode) {
this.sampleNode = sampleNode;
}
//Some methods
}
通常,(与我的其他通用类一起),假设它将类型传递给其构造函数,我通过执行以下操作来调用它:
BinaryTree<Integer> myTree=new BinaryTree<Integer>(Integer.class);
但是当然这是行不通的,因为它想要扩展BTNode
Node
类型。 我将如何引用扩展BTNode
的Node
以便创建BinaryTree
的实例?
如果稍微更改BTNode
类的类型参数,则有可能:
class BinaryTree<Node extends BinaryTree.BTNode>
{
static class BTNode<T> {
T value;
public BTNode<T> left;
public BTNode<T> right;
public BTNode<T> parent;
BTNode(T value) {
this.value = value;
}
}
private Node root;
public BinaryTree(Node node) {
root = node;
}
}
和用法:
class CustomNode extends BinaryTree.BTNode<Integer> {
CustomNode(Integer value) {
super(value);
}
}
BinaryTree<CustomNode> bt = new BinaryTree<>(new CustomNode(10));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.