1
class Jaguar 
{
void method(Object o)
{
    System.out.println("Object Called");
}
void method(String s)
{
    System.out.println("String Called");
}
public static void main(String[] args) 
{
    Jaguar j=new Jaguar();
    j.method(null);
}
}

Question:The o/p of the code is String Called and not ObjectCalled..Why?? null value is applicable to objects also..

Ashu Sinha
  • 19
  • 1
  • Object is the highest class available. But if a subclass is available, it will be called. Moreover, everything is firstly convert to String (if available), not to Object. You'll mostly have to cast to Object. – user388229 Jun 24 '17 at 07:14

1 Answers1

2

Java will always try to use the most specific applicable version of a method that's available see: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5

Object and String can all take null as a valid value. Therefore all 3 version is applicable, so Java will have to find the most specific one.

Since Object is the supertype of String, the String version is more specific than the Object-version. So if only those two methods exist, the String version will be chosen.

Each pair of these three methods is ambiguous by itself when called with a null argument. Because each parameter type is a reference type.

The following are the three ways to call one specific method of yours with null.

doSomething( (Object) null);
doSomething( (String) null);

If you add one more method with object subclass example Integer then the compiler will throw ambiguous method error as in that case compiler cannot decide if which method can be called string one or integer one.

I hope this helps.

Shivang Agarwal
  • 1,825
  • 1
  • 14
  • 19