Hi Ganesh,
Both the codes that you have given will not compile and the reason as stated by Dantheman is, incorrect usage of 'instanceof' operator
The syntax is <refrence> instanceof <object type>
you cannot use instanceof operator for <reference> instanceof <reference>.
public class MapIt
{
public <T extends Comparable<T>> T findLarger(T z , T y1)
{
if(z instanceof
Comparable)
// LINE x1 {
if(z.compareTo(y1) > 0)
{return z;}
else
{return y1;}
}
else
{
System.out.println("Check your arguments, they are not related to each other");
return null;
}
}
public static void main(
String args[])
{
MapIt t = new MapIt();
Object x = t.findLarger("123", "456");
System.out.println(x);
x = t.findLarger(123, 333);
System.out.println(x);
//This shoud throw exception
x = t.findLarger("123", 333);//LINE x2 System.out.println(x);
float fx=12;
float fy = 13;
x = t.findLarger(fx, fy);
System.out.println(x);
}
}
In the above code if you comment out line x2 this code will compile fine and give you the output.
Reason why line x2 doesnot compile is you are passing arguments of two
different type i.e findLarger(String, int), the compiler does not find method with this signature so it gives you error.
One more point that I would like to add here is,
there is no need of instanceof test. Like you said you want comparison to be done only when x and y are comparable, your method's signature is
findLarger(T, T) so obviously compiler will not allow any other type of parameter to be passed other than
T, not even a supertype of T or subtype of T. It will STRICTLY require parameter of type T to be passed.
I hope this clears why your code was not compiliing and running.
Thanks,
Rancy