Video in progress

Strong Junior 🧱 OOP and SOLID

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 of obj (Object). Overload selection is static, and the actual runtime type is not considered. That is the key difference from overriding.
  • print(null): null fits both parameters. The compiler picks the most specific variant: String is a subtype of Object, so the String version 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):

  1. methods that match without boxing/varargs;
  2. then with boxing/unboxing;
  3. 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.