I have a quick and straighforward question:
I have this simple class:
public class A
{
public void m(Object o)
{
System.out.println("m with Object called");
}
public void m(Number n)
{
System.out.println("m with Number called");
}
public static void main(String[] args)
{
A a = new A();
// why will m(Number) be called?
a.m(null);
}
}
UPDATE: actually is method with Number actually being called. Sorry about the confusion.
If I call a.m(null) it calls method with Number parameter.
My question is: why is this? where in the java language specification is this specified?
My 2 cents. Method with Number argument is the one that is called, Because Number extends Object. I had a similar situation in the past, I did override a method and put Component instead of JComponent (by mistake). It took me one week to find out the reason why my method was never called. I figure it out, that if there are some inheritance relationship between the overloaded methods, the JVM matches first the deeper one in the class hierarchy.
First of all, it actually calls
m(Number)
.It happens because both methods are applicable, but
m(Number)
is the most specific method, since any argument ofm(Number)
can be passed tom(Object)
, but not vice versa.If you replace
m(Object)
bym(String)
(or add another method such asm(Date)
), compiler would report ambiguity, since the most specific method can't be identified.See the section Choosing the Most Specific Method in the Java Specification.
Object
is the default type in Java. If you refactor yourm(Object o)
method tom(String o)
you'll have a compile time error saying that the callm(null)
is ambiguous because Java cannot determine which class betweenString
andNumber
defaults tonull
Other than that, between
m(Object o)
andm(Number o)
, callingm(null)
will callm(Number o)
because it's the most specialized method. You would need to castnull
into anObject
(or anything not an instance ofNumber
) otherwise.another related question for you to think about: