javagenericswildcardbounded-wildcard

Cannot Instantiate Type in generics


I have this class

public class Tree<T> {
    
    //List of branches for this tree
    private List<Tree<? super T>> branch = new ArrayList<Tree<? super T>>();
    public Tree(T t){ this.t = t; }
    public void addBranch(Tree< ? super T> src){ branch.add(src); }
    public Tree<? extends T> getBranch(int branchNum){
        return (Tree<? extends T>) branch.get(branchNum);
    }
    
    
    private T t;

}

And I am trying to create a variable out of this class using this

public static void main(String[] args){ 
        Tree<? super Number> num2 = new Tree<? super Number>(2);
    }

and it is giving me this error

Cannot instantiate the type Tree<? super Number>

Solution

  • While instantiating generics should be replaced with corresponding objects.

    Ex:

     Tree<Integer> num2 = new Tree<Integer>(2);