我必须做一些与粘贴的代码类似的东西,我有两个选择。在类定义中具有泛型的那个(其结果是一些警告)和下面的一个。
由于类型擦除,我无法使用后代的实现覆盖基本方法。
你认为这是一种正确而安全的方法吗?
public class Main {
public static void main(String args[]) {
List<Animal> animals = Arrays.asList(new Dog(), new Cat(), new Dog());
Map<Class<? extends Animal>, SoundPrinter> printers = new HashMap<Class<? extends Animal>, SoundPrinter>();
printers.put(Dog.class, new SoundDogPrinter());
printers.put(Cat.class, new SoundCatPrinter());
for (Animal animal:animals){
SoundPrinter printer = printers.get(animal.getClass());
System.out.println(printer.print(animal));
}
}
}
class Animal {
public String sound() {
return "animal sound";
}
}
class Dog extends Animal {
public String sound() {
return "dog sound";
}
}
class Cat extends Animal {
public String sound() {
return "cat sound";
}
}
abstract class SoundPrinter {
public <T extends Animal> String print(T animal) {
return "basic: " + animal.sound();
}
}
class SoundDogPrinter extends SoundPrinter {
public String print(Dog dog) {
return "dog's processed sound: " + dog.sound();
}
}
class SoundCatPrinter extends SoundPrinter {
public String print(Cat dog) {
return "cat's processed sound: " + dog.sound();
}
}
答案 0 :(得分:0)
您拥有它的方式,print
和SoundDogPrinter
中的SoundCatPrinter
方法无法覆盖print
中的SoundPrinter
。
类本身需要是通用的,而不是类中的方法。这样,print
方法实际上将在SoundDogPrinter
和SoundCatPrinter
类中被覆盖。
abstract class SoundPrinter<T extends Animal> {
public String print(T animal) {
return "basic: " + animal.sound();
}
}
class SoundDogPrinter extends SoundPrinter<Dog> {
public String print(Dog dog) {
return "dog's processed sound: " + dog.sound();
}
}
class SoundCatPrinter extends SoundPrinter<Cat> {
public String print(Cat dog) {
return "cat's processed sound: " + dog.sound();
}
}