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…
Question
- public abstract class Animal
- public interface Hunter
- public class Cat extends Animal implements Hunter
- public class Tiger extends Cat
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)- A3% (1)
- B6% (2)
- C12% (4)
- D79% (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
Community Discussion
No community discussion yet for this question.