Tôi có thể giải thích điều này ở đâu?Java Generics: thêm sai loại trong bộ sưu tập
Tôi có những cặp vợ chồng các lớp:
abstract class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
public void woof() {
System.out.println("woof");
}
}
class Cat extends Animal {
public void meow() {
System.out.println("meow");
}
}
Và đây là hành động:
import java.util.ArrayList;
import java.util.List;
public class TestClass {
public static void main(String[] args) {
new TestClass().go();
}
public void go() {
List<Dog> animals = new ArrayList<Dog>();
animals.add(new Dog());
animals.add(new Dog());
doAction(animals);
}
public <T extends Animal> void doAction(List<T> animals) {
animals.add((T) new Cat()); // why is it possible?
// Variable **animals** is List<Dog>,
// it is wrong, that I can add a Cat!
for (Animal animal: animals) {
if (animal instanceof Cat) {
((Cat)animal).meow();
}
if (animal instanceof Dog) {
((Dog)animal).woof();
}
}
}
}
Ví dụ này biên dịch mà không có lỗi, và đầu ra là:
woof
woof
meow
Nhưng làm thế nào thế nào tôi có thể thêm vào danh sách Dog a Cat? Và làm thế nào Mèo được đúc cho chó?
Tôi sử dụng: phiên bản java "1.6.0_24". Môi trường chạy OpenJDK (IcedTea6 1.11.1) (6b24-1.11.1-4ubuntu3)
Có cảnh báo trình biên dịch, không? –
Chắc chắn sẽ có một cảnh báo trình biên dịch trên animals.add ((T) new Cat()) ;. – tjg184
Và vì vậy hãy bắt đầu đường mòn của nước mắt đó là Generics Java. –