gpt4 book ai didi

java - 抽象类和泛型中 "this"关键字的行为

转载 作者:行者123 更新时间:2023-12-02 02:00:53 25 4
gpt4 key购买 nike

考虑以下类

就序列化而言,重新发明轮子,我知道:

abstract class AnimalSerializer<E extends Animal> {
/**
* The type E (which extends Animal) is important here.
* I want to be able to write data that is specific to a subclass of an animal.
*/
abstract void writeAnimal(E animal);
abstract Animal readAnimal();
}

abstract class Animal {
AnimalSerializer<? extends Animal> serializer;

Animal(AnimalSerializer<? extends Animal> speciesSerializer) {
serializer = speciesSerializer;
}

void writeAnimalToFile() {
// This line fails to compile
serializer.writeAnimal(this);
}
}

这些类演示了此模式的用法:

class DogSerializer extends AnimalSerializer<Dog> {

@Override
void writeAnimal(Dog animal) {
// Write the stuff that is specific to the dog
// ...
}

@Override
Animal readAnimal() {
// Read the stuff specific to the dog, instantiate it, and cast it as an animal.
// ...
return null;
}
}

class Dog extends Animal {
String dogTag = "Data specific to dog.";

Dog() {
super(new DogSerializer());
}
}

我的问题与编译失败的行( serializer.writeAnimal(this) )有关。我必须第一次调出语言规范才能了解有关 this 的更多信息。关键字,但我认为问题在于“this”关键字的类型为 Animal ,以及有界通配符泛型 <? extends Animal>仅支持 Animal 子类的类型,而不支持 Animal输入自己。

我认为编译器应该知道 this 的类型关键字必须是一个扩展 Animal 的对象,因为 Animal 无法实例化,并且 this关键字仅适用于已经存在的对象。

编译器无法知道这一点是否有原因?我的猜测是有一个案例可以解释为什么this不能保证关键字是 Animal 的子类。

此外,这种模式是否存在根本缺陷?

最佳答案

您的序列化器泛型类型是?扩展动物。你的this类型是Animal,它也可以被认为是?扩展动物。但这两个?是不同的类型。没有任何限制让编译器知道它们是相同的类型。

例如,我写了一个Cat

class Cat extends Animal {
Cat(){
super(new DogSerializer()); // this is ok for your generic
}
}

这就是编译器给你一个错误的原因。

关于java - 抽象类和泛型中 "this"关键字的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51606834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com