Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
976 views
in Technique[技术] by (71.8m points)

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.


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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...