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());
}
}- A. Compilation error: asDouble() is undefined for T
- B. 5.0
- C. 5
- 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
- What is printed? java class Util { static <T> void swap(T[] arr, int i, int j) { T tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } public…
- What is printed? java public class Main { static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } public…
- Which statement is correct about this class? java public class Base { public void show() { } } class Sub extends Base { private void…
- Which statement is correct? java class Base { protected void configure() { } } class Derived extends Base { public void configure() { } }
- Which statement is correct? java final class Immutable { void f() { } } class Sub extends Immutable { }
- Which statement is correct? java class Base { final void process() { System.out.print("Base.process"); } } class Sub extends Base { void…