javagenericstype-parametergeneric-method

sending a generic class object to a generic method (java)


I have a class named InstanceClass as follows:

package trials;

public class InstanceClass<T>  {

    private T num;

    public void calculate() {
        System.out.printf("%s", num);
    }
    public T getNum() {
        return num;
    }

    public void setNum(T num) {
        this.num = num;
    }

    public InstanceClass(T num) {
        super();
        this.num = num;
    }
}

and Trial class in which the main method located as follows:

package trials;

public class TrialClass {

    public static void main(String[] args) {

        InstanceClass<Integer> my=new InstanceClass<>(2);
        InstanceClass<InstanceClass<Integer>> x=new InstanceClass<>(my);
        prt(x.getNum());
    }
    
    public static <T extends InstanceClass<Integer>> void prt(T q) {
        System.out.printf("%s%n",q.getNum());
        q.calculate();
    }
}

So, I want to know why can't we simply use <T> instead of <T extends InstanceClass<Integer>> in the method prt's declaration.


Solution

  • If you change

    public static <T extends InstanceClass<Integer>> void prt(T q)
    

    to

    public static <T> void prt(T q)
    

    the compiler wouldn't know that the type parameter T must be an InstanceClass, and therefore it wouldn't know that it has getNum() and calculate() methods, which you are trying to call from prt.

    In fact, the compiler would allow you to pass to the prt method any argument, including instances of classes unrelated to InstanceClass, which don't have the methods you are trying to call inside prt.