Calling a general method from a subclass in java

I am 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 use Tree <Data> in DataTree correctly to call special DataTree methods?

+4
source share
2 answers

DataTree Tree<Data> , but Tree<Data> not always a DataTree .

You are returning a Tree<T> , not a DataTree . The base class cannot be dropped into the derrive class.

+5
source

what is root ??? is it a data item?

Try listing DataTree dataTree = (DataTree) this.getTree (root)

Well, I think the inheritance hierarchy will not support this, but you can still try.

0
source

All Articles