ProgrammingVery hardProduct-company placement · Java
What happens when this class is compiled?
What happens when this class is compiled?
class Code implements Comparable<String>, Comparable<Integer> {
public int compareTo(String s) { return 0; }
public int compareTo(Integer i) { return 0; }
}- A. Compile-time error: Comparable cannot be implemented with two different type arguments
- B. It compiles; the overload is chosen by argument type
- C. It compiles but sorting throws ClassCastException
- D. Compile-time error only because both compareTo return 0
Correct answer: A. Compile-time error: Comparable cannot be implemented with two different type arguments
After erasure both are the same interface Comparable, so a class may not implement two different parameterisations of one generic interface (and the two bridge methods would clash).
More OOP with C++ and Java questions
- Which statement about Java anonymous classes is correct?
- Which lines fail to compile? java // Java 10 or later var list = new ArrayList<>(); // L1 list.add(1); list.add("a"); // L2 var x; // L3…
- What happens when this is compiled? java // Java 17 sealed class Shape permits Circle, Square { } final class Circle extends Shape { }…
- What is printed? java class AppEx extends Exception { } class DbEx extends AppEx { } // static method of the main class: static void run()…
- What is printed? java // in main, which is declared throws Exception: try (AutoCloseable r = null) { System.out.print("body"); }…
- How many of these statements are correct in Java? (i) A subclass object contains storage for its superclass's private fields. (ii) A…