0

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);
}

}
6
  • 1
    What do you think <Integer> in public static <Integer> void does? Why do you think so? Commented May 12, 2016 at 17:54
  • <Integer> --> Shouldn't this tell the compiler to call the m1 which accepts 'Integer'? Since Integer is subclass of Object(probably) I can understand why the call goes to Object, but if I delete the m1(Object s) the code does not compile. Commented May 12, 2016 at 17:57
  • That's a method declaration. It doesn't call anything. Have you learned about generic methods yet and how they declare generic type parameters? Commented May 12, 2016 at 17:57
  • 2
    @Akash_Bandyopadhyay No, <Integer> creates a named generic type (and that then shadows java.lang.Integer). Why are you making that a generic method? And why did you name the type Integer? Commented May 12, 2016 at 17:58
  • You only named the generic type Integer. To illustrate, these two declarations are the same: <Integer> void m2(Integer t) and <Foo> void m2(Foo t) Commented May 12, 2016 at 18:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

In addition to that you can cast the variable to control the execution of the right method, e.g. Test.m2((Integer)Integer.valueOf(12)); or Test.m2((Object)Integer.valueOf(12));. That technique calls polymorphism.
I tried that. But it still goes to m1(object s), however if I cast it to integer inside definition of m2, then it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.