Dmitriy
Dmitriy

Reputation: 41

Calling generic method from subclass in java

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?

Upvotes: 4

Views: 155

Answers (2)

Rahul Razdan
Rahul Razdan

Reputation: 429

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 .

Upvotes: -1

Dmitry Zaytsev
Dmitry Zaytsev

Reputation: 23952

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.

Upvotes: 5

Related Questions