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);- A. OON
- B. INN
- C. INO
- 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
- A base type must hold common fields, have a constructor that validates them, and share some method bodies, while subclasses form a strict…
- java.io.BufferedReader wraps another Reader, is itself a Reader, and adds buffering on top of it; such wrappers can be stacked at run…
- Collections.sort(list, comparator) lets the caller pass the comparison algorithm as an object, and the same sort code works with any…
- Square extends Rectangle and overrides setWidth and setHeight so that both always change together. Client code written for Rectangle does…
- A Department has Professors who continue to exist if the department is closed, while a House is made of Rooms that cannot exist without…
- What is printed? java // static methods of the main class: static void p(Object o) { System.out.print("O"); } static void p(String s) {…