泛型继承
我正在尝试在 Java 中实现具有任意键的递归树结构。基本上我想要的是拥有一个 Tree
,其中包含一个 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
的子类,它不应该有权访问其父类的受保护字段吗?
感谢您的任何帮助。
I am trying to implement a recursive tree structure with arbitrary keys in Java. Basically what I want is to have a Tree<X,Y>
which holds an X
and more (sub)Trees, indexed by a set of Y
s. However, I think that since the trees will be used for indexing data in a readonly disk file, the Tree itself should be read-only. So, in order to create them, I made a subclass, MutableTree
, which should allow editing operations on a Tree
.
Here is my code:
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);
}
}
And for the 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;
}
}
This snippet does not compile, opting instead to complain that Tree.content
and Tree.nexts
are protected. As you can see, they indeed are. However, as MutableTree
is a subclass of Tree
, shouldn't it have access to its parent's protected fields?
Thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只能通过与您的代码或子类型相同类型的引用来访问
受保护
成员。就像您的情况一样,因为创建
MutableTree
将允许客户端代码改变假定不可变的Tree
。You can only access
protected
members through references of the same type as your code, or subtype.Just as well in your case, because creating a
MutableTree
would allow client code to mutate a supposedly immutableTree
.