Method selection at compile time. What if the parameter can have several types?
-
27-10-2019 - |
Question
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?
Solution
An expression such as
action == 0 ? "" : action
can have a single return type. The compiler understands this as an expression returning an Object
instance. This, at runtime, can be either String
or Integer
.
In your case, append(Object)
will be called. The StringBuilder implementation will then call toString()
on the parameter, which will give you the expected result (either ""
or an integer value converted to String).
OTHER TIPS
StringBuilder has a many overloaded methods called append. So there is a different append for most type. Any other type is an Object.
StringBuilder append(boolean b)
Appends the string representation of the boolean argument to the sequence.
StringBuilder append(char c)
Appends the string representation of the char argument to this sequence.
StringBuilder append(char[] str)
Appends the string representation of the char array argument to this sequence.
StringBuilder append(char[] str, int offset, int len)
Appends the string representation of a subarray of the char array argument to this sequence.
StringBuilder append(CharSequence s)
Appends the specified character sequence to this Appendable.
StringBuilder append(CharSequence s, int start, int end)
Appends a subsequence of the specified CharSequence to this sequence.
StringBuilder append(double d)
Appends the string representation of the double argument to this sequence.
StringBuilder append(float f)
Appends the string representation of the float argument to this sequence.
StringBuilder append(int i)
Appends the string representation of the int argument to this sequence.
StringBuilder append(long lng)
Appends the string representation of the long argument to this sequence.
StringBuilder append(Object obj)
Appends the string representation of the Object argument.
StringBuilder append(String str)
Appends the specified string to this character sequence.
StringBuilder append(StringBuffer sb)