fmt
fmt

Reputation: 993

Inheritance with Generics

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 Ys. 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.

Upvotes: 0

Views: 178

Answers (1)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

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 immutable Tree.

Upvotes: 3

Related Questions