ProgrammingHardAmazon/Microsoft SDE MCQ · Java placement
Which line fails to compile?
Which line fails to compile?
class Animal { Animal make() { return new Animal(); } }
class Dog extends Animal {
Dog make() { return new Dog(); } // line 1
}
class Cat extends Animal {
Object make() { return new Cat(); } // line 2
}
class Fox extends Animal {
protected Animal make() { return this; } // line 3
}- A. Line 1
- B. Line 2
- C. Line 3
- D. Lines 2 and 3
Correct answer: B. Line 2
An override may narrow the return type to a subtype (covariant return, line 1) and may widen access from package-private to protected (line 3). Returning Object, a supertype of Animal, is not allowed.
More OOP with C++ and Java questions
- 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…
- What is printed? java List<Integer> l = new ArrayList<>(List.of(5, 6, 7)); Iterator<Integer> it = l.iterator(); while (it.hasNext()) if…
- What does this Java program print? class A { String n = "A"; String get() { return n; } } class B extends A { String n = "B"; String get()…