ProgrammingVery hardProduct-company placement · Java

What is printed?

What is printed?
// static methods of the main class:
static void f(Object o)  { System.out.print("O"); }
static void f(Number n)  { System.out.print("N"); }
static void f(Integer i) { System.out.print("I"); }
// in main:
f(null); f((Number) null); f(5L);
  1. A. OON
  2. B. INN
  3. C. INO
  4. D. Compile-time error: f(null) is ambiguous

Correct answer: B. INN

Integer ⊂ Number ⊂ Object form a chain, so for null the most specific, f(Integer), wins. The cast fixes the static type to Number. 5L cannot widen to any parameter, so it is boxed to Long, which fits Number (more specific than Object) but not Integer.

More OOP with C++ and Java questions

Exams that ask this topic