I am led to believe that the java compiler does all the work of method selection at compile time (or am I wrong?). That is, it will decide exactly which method to use in which class at compile time by examining the class hierarchy and method signatures. All that is then required at run time is to choose the object whose method is to be called and this can only work up the inheritance chain.
If that is the case, how does this work?
int action = getAction ();
StringBuilder s = new StringBuilder()
.append("Hello ") // Fine
.append(10) // Fine too
.append(action == 0 ? "" : action); // How does it do this?
Here, the type of the parameter can be either String or int. How can it decide at compile time which method of StringBuilder should be invoked?
An expression such as
can have a single return type. The compiler understands this as an expression returning an
Objectinstance. This, at runtime, can be eitherStringorInteger.In your case,
append(Object)will be called. The StringBuilder implementation will then calltoString()on the parameter, which will give you the expected result (either""or an integer value converted to String).