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?
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.
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.