Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism and method overloading

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?

like image 361
jrey Avatar asked Feb 10 '11 18:02

jrey


People also ask

What is difference between polymorphism and method overloading?

Polymorphism is the process to define more than one body for functions/methods with same name. Overloading IS a type of polymorphism, where the signature part must be different. Overriding is another, that is used in case of inheritance where signature part is also same.

What is the difference between polymorphism and method overriding?

Polymorphism is a concept of object oriented programming that allows a field, in this case, an object, to be changed from one form to another. Poly = multiple, morph = change. Overriding a method, is essentially a dynamic binding of a method which allows a method to be changed during run-time.

What is polymorphism method overloading and method overriding?

Polymorphism. Method Overloading is used to implement Compile time or static polymorphism. Method Overriding is used to implement Runtime or dynamic polymorphism. Purpose. It is used to expand the readability of the program.


1 Answers

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 of m(Number) can be passed to m(Object), but not vice versa.

If you replace m(Object) by m(String) (or add another method such as m(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.

like image 63
axtavt Avatar answered Oct 01 '22 06:10

axtavt