Issue
I'm puzzled how Java polymorphism works.
In the case below, there are three polymorphism methods of showText
, for distinguishing clearly, these methods names method-1
, method-2
, method-3
. codes as below:
public class PolymorphismTest {
public static void main(String[] args) {
showText("def");
}
// method-1
private static void showText(Object abc) {
print("1.....");
showText(abc, "abc");
}
// method-2
private static void showText(Object abc, String item) {
// print(abc.getClass().getName());
print("2.....");
String text;
if (abc == null) {
text = null;
} else {
text = abc.toString();
}
showText(text, item);
}
// method-3
private static void showText(String abc, String item) {
print("3.....");
}
private static void print(String text) {
System.out.print(text);
}
}
- method-1 has one parameter of type
Object
- method-2 has two parameters, the parameter type are
Object
andString
- method-3 has two parameters, the same param count with
method-2
, while its first param type isString
The main()
calls method-1
with a parameter of type String
, in the body of method-1
it calls another method, which one is matched, method-2
or method-3
?
I test it in java 8, the out put is
1.....2.....3.....
Solution
Overload is decided at compile-time, so when the first method gets the abc
parameter it sees it as an Object
(not a String
) and calls method-2
which has the appropriate signature for it.
You are probably confused because this is different from the dynamic linking mechanism, which applies to class instances (objects) methods, and resolves the method at runtime based on the actual class of the instance on which the call is made (for example toString()
in abc.toString()
).
Answered By - kgautron
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.