ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Holder<T extends Number> {
    T value;
    Holder(T v) { value = v; }
    double asDouble() { return value.doubleValue(); }
}
public class Main {
    public static void main(String[] args) {
        Holder<Integer> h = new Holder<>(5);
        System.out.print(h.asDouble());
    }
}
  1. A. Compilation error: asDouble() is undefined for T
  2. B. 5.0
  3. C. 5
  4. D. Compilation error: Integer is not a subtype of Number

Correct answer: B. 5.0

The bound `T extends Number` guarantees any T has Number's methods, including doubleValue(), so the compiler accepts value.doubleValue() without a cast. Integer extends Number, so Holder<Integer> is legal, and asDouble() returns 5.0.

More OOP with C++ and Java questions

Exams that ask this topic