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
?
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() { ... }
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With