nerdexam
Oracle

1Z0-808 · Question #24

Given the following class declarations: public abstract class Animal public interface Hunter public class Cat extends Animal implements Hunter public class Tiger extends Cat Which answer fails to…

The correct answer is D. ArrayList<Tiger> myList = new ArrayList<>(); myList.add(new Cat()). D fails because Cat is a superclass of Tiger, not a subtype. ArrayList<Tiger> only accepts Tiger objects (or subclasses of Tiger), and Cat does not qualify - the relationship runs the wrong direction. Java generics are invariant: ArrayList<Tiger> is not a subtype of…

Working with Inheritance

Question

Given the following class declarations:
  • public abstract class Animal
  • public interface Hunter
  • public class Cat extends Animal implements Hunter
  • public class Tiger extends Cat
Which answer fails to compile?

Options

  • AArrayList<Animal> myList = new ArrayList<>(); myList.add(new Tiger());
  • BArrayList<Hunter> myList = new ArrayList<>(); myList.add(new Cat());
  • CArrayList<Hunter> myList = new ArrayList<>(); myList.add(new Tiger());
  • DArrayList<Tiger> myList = new ArrayList<>(); myList.add(new Cat());
  • EArrayList<Animal> myList = new ArrayList<>(); myList.add(new Cat());

How the community answered

(33 responses)
  • A
    3% (1)
  • B
    6% (2)
  • C
    12% (4)
  • D
    79% (26)

Explanation

D fails because Cat is a superclass of Tiger, not a subtype. ArrayList<Tiger> only accepts Tiger objects (or subclasses of Tiger), and Cat does not qualify - the relationship runs the wrong direction. Java generics are invariant: ArrayList<Tiger> is not a subtype of ArrayList<Cat>, and you cannot add a Cat where a Tiger is required.

Why the distractors compile: A and E work because both Tiger and Cat are subclasses of Animal (Tiger inherits through Cat). B and C work because both Cat and Tiger implement Hunter - Tiger inherits that implementation from Cat. In all four cases, the object being added is the declared generic type or a subtype of it.

Memory tip: Flip the "is-a" question. Ask "Is the object I'm adding a [declared type]?" - Tiger is an Animal, a Cat, and a Hunter; but a Cat is not a Tiger. If the answer is no, it won't compile.

Topics

#Generic Collections#Inheritance#Type Compatibility#Polymorphism

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice