Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
842 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...