ProgrammingVery hardProduct-company placement · Java

Which line fails to compile?

Which line fails to compile?
class Fruit implements Comparable<Fruit> { public int compareTo(Fruit o) { return 0; } }
class Apple extends Fruit { }
// static methods of the main class:
static <T extends Comparable<T>> T max1(List<T> l) { return l.get(0); }
static <T extends Comparable<? super T>> T max2(List<T> l) { return l.get(0); }
// in main:
List<Apple> apples = List.of(new Apple());
max1(apples);   // L1
max2(apples);   // L2
  1. A. L2 only
  2. B. Both
  3. C. L1 only
  4. D. Neither

Correct answer: C. L1 only

Apple is Comparable<Fruit>, not Comparable<Apple>, so T = Apple violates T extends Comparable<T>. The bound Comparable<? super T> accepts comparability inherited from a supertype; this is why Collections.max uses it.

More OOP with C++ and Java questions

Exams that ask this topic