Given the following class declarations:
public abstract class Animal
public interface Hunter
public class Cat extends Animal implements Hunter
public class Tiger extends Cat
public interface Hunter
public class Cat extends Animal implements Hunter
public class Tiger extends Cat
Which answer fails to compile?
A.
ArrayList<Animal> myList = new ArrayList<>();
myList.add(new Tiger());
B.
ArrayList<Hunter> myList = new ArrayList<>();
myList.add(new Cat());
C.
ArrayList<Hunter> myList = new ArrayList<>();
myList.add(new Tiger());
D.
ArrayList<Tiger> myList = new ArrayList<>();
myList.add(new Cat());
E.
ArrayList<Animal> myList = new ArrayList<>();
myList.add(new Cat());
題解
選項A,Tiger是Animal(Tiger繼承Cat,Cat繼承Animal),所以這沒有問題。
選項B,Cat是Hunter(Cat繼承Animal),所以這沒有問題。
選項C,Tiger是Hunter(Tiger繼承Cat,Cat實作Hunter),所以這沒有問題。
選項D,Cat不是Tiger,會編譯錯誤。
選項E,Cat是Animal(Cat繼承Animal),所以這沒有問題。