public class Test1 {
public static void main(String[] args) {
Test1 test1 = new Test1();
test1.testMethod(null);
}
public void testMethod(String s){
System.out.println("Inside String Method");
}
public void testMethod(Object o){
System.out.println("Inside Object Method");
}
}
When I try to run the given code, I get the following output:
Inside String Method
Can anyone explain why the method with the String
type parameter is getting called?
Two or more methods can have the same name inside the same class if they accept different arguments. This feature is known as method overloading. Method overloading is achieved by either: changing the number of arguments.
Benefits of using Method Overloading Method overloading increases the readability of the program. This provides flexibility to programmers so that they can call the same method for different types of data. This makes the code look clean.
most specific method argument is chosen for overloaded methods
In this case, String
is subclass of Object
. Hence String
becomes more specific than Object
. Hence Inside String method
is printed.
Directly from JLS-15.12.2.5
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
As BMT and LastFreeNickName have correctly suggested, (Object)null
will cause overloaded method with Object
type method to be called.
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