Java – how do overloaded methods work?
•
Java
public class Test1 {
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:
Anyone can explain why a method using a string type parameter is called?
Solution
The most important method is to select the most specific method parameters
In this case, string is a subclass of object Therefore, string becomes more specific than object Therefore, the inside string method is printed
Directly from jls-15.12 two point five
As BMT and lastfreenickname correctly prompt, (object) null will cause overloaded methods using the object type method to be called
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码