我正在尝试在Java中实现具有任意键的递归树结构。基本上我想要的是有一个 Tree<X,Y>
其中包含 X
和更多(子)树,由一组 Y
索引s。但是,我认为由于树将用于索引只读磁盘文件中的数据,因此树本身应该是只读的。因此,为了创建它们,我创建了一个子类 MutableTree
,这应该允许对 Tree
进行编辑操作.
这是我的代码:
public class Tree<C,K> implements Serializable {
protected C content;
protected java.util.HashMap<K, Tree<C,K>> nexts;
protected Tree () {}
public C getContent() {
return content;
}
public java.util.Iterator<K> getKeys () {
return nexts.keySet().iterator();
}
public Tree<C,K> descend(K key) {
return nexts.get(key);
}
}
对于 MutableTree
:
public class MutableTree<C,K> extends Tree<C,K> {
public MutableTree (Tree<C,K> par) {
super();
this.content = par.content;
this.nexts = par.nexts;
}
public MutableTree () {
super();
}
public void setContent (C c) {
this.content = c;
}
public MutableTree<C,K> addKey (K k) {
MutableTree<C,K> noo = new MutableTree<C,K>();
nexts.put(k, noo);
return noo;
}
public boolean delKey (K k) {
return (nexts.remove(k)!=null)?true:false;
}
}
此代码片段无法编译,而是选择提示 Tree.content
和Tree.nexts
受到保护。正如您所看到的,它们确实是。然而,如MutableTree
是 Tree
的子类,它不应该有权访问其父级的 protected 字段吗?
感谢您的帮助。
最佳答案
您只能通过与您的代码或子类型相同类型的引用来访问 protected
成员。
就像您的情况一样,因为创建 MutableTree
将允许客户端代码改变所谓不可变的Tree
。
关于java - 泛型继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4330978/