Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type conversion and method overloading

This is the sample code :

public class OverloadingExample {
public void display(Object obj){
    System.out.println("Inside object");
}

public void display(Double doub){
    System.out.println("Inside double");
}

public static void main(String args[]){
    new OverloadingExample().display(null);
}
}

Output:

Inside double

Can anyone please explain me why the overloaded method with Double parameter is called instead of that with Object ?

like image 229
AllTooSir Avatar asked Feb 04 '12 10:02

AllTooSir


People also ask

What is method overloading and example?

In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading. For example: void func() { ... }

What are the different types of method overloading?

There are two types of Polymorphism: Method Overloading and Method Overriding. Method overloading means multiple methods are having the same name but different arguments. Method Overriding means the child class can have a method with the same name as the parent class but with a different implementation.

What is the difference between method overloading and method overriding?

In method overloading, methods must have the same name and different signatures. In method overriding, methods must have the same name and same signature. In method overloading, the return type can or can not be the same, but we just have to change the parameter.

What is method overloading in oops?

Method overloading is a form of polymorphism in OOP. Polymorphism allows objects or methods to act in different ways, according to the means in which they are used. One such manner in which the methods behave according to their argument types and number of arguments is method overloading.


1 Answers

Yes - because Double is more specific than Object. There's a conversion from Double to Object, but not the other way round, which is what makes it more specific.

See section 15.12.2.5 of the JLS for more information. The details are pretty hard to follow, but this helps:

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

So here, any invocation of display(Double doub) could be handled by display(Object obj) but not the other way round.

like image 81
Jon Skeet Avatar answered Oct 15 '22 19:10

Jon Skeet