4

I'm new to generics and here is my problem:

public class Tree<T> { public Collection<Tree<T>> getSubTrees(){}; public Tree<T> getTree(T element){} } public class DataTree extends Tree<Data>{ public void someMethod(){ DataTree dataTree = this.getTree(root) ;// type mismatch Collection<DataTree> leafs = this.getSubTrees(); //type mismatch //following works Tree<Data> dataTree = this.getTree(root); Collection<Tree<Data>> leafs = this.getSubTrees(); } } 

Can you tell me why I got such errors or how to correctly cast Tree<Data> to DataTree to call DataTree specific methods?

2 Answers 2

5

DataTree is Tree<Data> but Tree<Data> is not always DataTree.

You are returning Tree<T>, not DataTree. Base class cannot be casted to derrived class.

Sign up to request clarification or add additional context in comments.

1 Comment

The traditional way to fix this, by the way, is to add an additional generic parameter to Tree: something like Tree<E, T extends Tree<E>>, and then to have the children be of type T. Then you can "tie the knot" by saying class DataTree extends Tree<Data, DataTree>.
-1

what is root??? is it a Data Element??

Try Type casting the
DataTree dataTree = (DataTree)this.getTree(root)

well i think Inheritance hierarchy will not support this , but still you can try .

1 Comment

here you are trying to cast your base class to derived class, that will not work , try fix that first

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.