简体   繁体   中英

Understanding java generic method

Output is always In OBJECT . since the return type is void in all cases.
But why is it not going to m1(Integer s)? And without typecasting is it possible to make the call go to m1(Integer s)?

package test;

public class test_class {

public static void m1(Integer s){
    System.out.println("IN INT");
}

public static void m1(Object s){
    System.out.println("IN OBJECT");        
}

public static <Integer> void m2(Integer t){
    m1(t);
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    test_class.m2(12);
}

}

I don't seem to understand how generics work, you somehow mix it up with overloading. If you declare a generic method, the type parameter (in your case Integer ) is be a variable (often T ). In your case, the type parameter is called Integer, which somehow interferes/shadows the type of the argument.

Just remove the <Integer> from m2 and you get the expected result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM