![](/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.