Video in progress
Which of these overloads gets called, and what is printed?
public class Printer {
static void print(Object o) { System.out.println("Object"); }
static void print(String s) { System.out.println("String"); }
public static void main(String[] args) {
Object obj = "salom";
print(obj);
print(null);
}
}
First Object, then String is printed. The overload is chosen at compile time by the declared type of the variable: obj is a variable of type Object, so it doesn't matter that it holds a String. print(null) picks the most specific type, the String version.
📖 Answer
The output:
Object
String
Why:
print(obj): the compiler sees only the declared type ofobj(Object). Overload selection is static, and the actual runtime type is not considered. That is the key difference from overriding.print(null):nullfits both parameters. The compiler picks the most specific variant:Stringis a subtype ofObject, so theStringversion wins.
If you also add print(Integer i), print(null) becomes a compile error: reference to print is ambiguous, because neither String nor Integer is a subtype of the other.
The overload resolution order (briefly):
- methods that match without boxing/varargs;
- then with boxing/unboxing;
- finally with varargs.
That is why, with void f(long x) and void f(Integer x), f(5) picks the long version: widening comes before boxing.
In practice: avoid overloads with the same number of parameters and closely related types. Clear names like printObject and printText are safer.
Sign up to mark studied questions and save your progress.