Hi,
Well this is really a very good question..a proper explanation to this will really clear your concept regarding wild card and type parameter in Generics:
let me try to explain how compiler use your code here..!!
This line has a quite complex meaning for compiler:
public <T extends Comparable> T findLarger(T x, T y) { lets break it in different part:
< T extends Comparable >
As per i think, Compiler use this to accept only those parameter which implements Comparable.
for ex: if you try to call this method by passing:
Object and Object --> compiler will not accept, because Object doesn't implements Comparable,but if you pass:
Integer and Integer --> Compiler will accept.
Integer and
String ---> Compiler will accept as both implements Comparable
Compiler treats both arguments differently..!!
This part has only this role.
return type T --> It can return only type T.
now lets consider your Problem option one by one:
Option 1)
A. Object x = t.findLarger(123, �456�);
now see
123 --> Integer --> implements Comparable
456 --> String ---> implements Comparable
Now how compiler can accept String and Integer ?
here compile do a conversion...it sees is there is something specific to both..
for eg:
Integer extends Object
String extends Object
So compiler see both as Object and accept them..so from compiler point of view:
T x ---> Object x --> Object x = new Integer(123)
T y ---> Object y --> Object y = new String(456);
and we can call Object.compareTo(Object)
again return type is int --> Integer --> extends Object
so this works fine.!!
/**********************************************/
Option 2)
B. int x = t.findLarger(123, new Double(456));
Here
123 ---> Integer ---> Number
456 ---> Double ----> Number
But problem is that we can not call : Number.compareTo(Number)
type mismatch between Number and comparable<?> --> Comparable< ? extends Object>
/*******************************************************/
Option 3)
C. int x = t.findLarger(123, new Integer(456));
since both are Integer here..so T refers to Integer..so rest is Obvious..
/****************************************************/
Option 4)
D. int x = (int) t.findLarger(new Double(123), new Double(456));
T refers to Double..
so return type is also Double..!!
and we can not convert double to int..inconvertible type..!!!
/*************************************************/
this all explanation was as per my understanding on the issue..!!!