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
}
  1. A. Line 1
  2. B. Line 2
  3. C. Line 3
  4. 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

Exams that ask this topic