ProgrammingVery hardAmazon/Microsoft SDE MCQ · Java placement
Why does this class fail to compile?
Why does this class fail to compile?
class Util {
static void f(List<String> l) { }
static void f(List<Integer> l) { }
}- A. Overloads may not differ only in a type argument, since both erase to f(List)
- B. It compiles; the compiler picks the overload from the type argument
- C. A static method may not take a generic parameter
- D. List<Integer> is not allowed because int is primitive
Correct answer: A. Overloads may not differ only in a type argument, since both erase to f(List)
Type arguments are erased, so both methods have the same erasure f(List) and would clash in the class file; the compiler reports a name clash. Generic parameters are otherwise allowed in static methods.
More OOP with C++ and Java questions
- What is printed? java record Pt(int x, int y) { } // in main: Set<Pt> s = new HashSet<>(); s.add(new Pt(1, 2)); s.add(new Pt(1, 2))…
- Which line fails to compile? java class Animal { Animal make() { return new Animal(); } } class Dog extends Animal { Dog make() { return…
- What is printed? java PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder()); pq.addAll(List.of(3, 1, 4, 1, 5))…
- A Printer interface declares print(), scan(), fax() and staple(). A cheap printer class must implement all four and throws…
- What is printed? java String a = "Hi"; String b = new String("Hi"); String c = b.intern(); StringBuilder d = new StringBuilder("Hi")…
- What is printed? java abstract class Shape { Shape() { System.out.print(area() + " "); } abstract double area(); } class Sq extends Shape…