gpt4 book ai didi

java - 使用需要假设 A 属于扩展 A 的类 B 而不必强制转换每个元素的版本覆盖方法 m(List listOfA)

转载 作者:行者123 更新时间:2023-12-03 18:17:20 26 4
gpt4 key购买 nike

刚遇到一个我以前没见过的建模问题。

假设我有一个针对法国人的类(class),另一个针对医生的类(class),另一个针对法国医生的类(class),我想编写以下内容:

///////// FRANCE

interface FrenchPerson {}

void frenchSpecificBureaucraticProcedure(List<? extends FrenchPerson> frenchPeople) {
// ...
}

///////// DOCTORS

interface Doctor {}

class DoctorsAssociation {
void includeNewMembers(List<? extends Doctor> doctors) {
// ... do stuff
}
}

///////// FRENCH DOCTORS

interface FrenchDoctor extends FrenchPerson, Doctor {}

class FrenchDoctorsAssociation extends DoctorsAssociation {

@Override
void includeNewMembers(List<? extends Doctor> frenchDoctors) {
// ERROR: frenchDoctors is List<? extends Doctors>
// but frenchSpecificBureaucraticProcedure requires List<? extends FrenchDoctor>
frenchSpecificBureaucraticProcedure(frenchDoctors);

super.includeNewMembers(frenchDoctors);
}
}

我的第一个冲动是覆盖 includeNewMembers使用 List<? extends FrenchDoctor>参数代替:

    @Override
void includeNewMembers(List<? extends FrenchDoctor> frenchDoctors) {
frenchSpecificBureaucraticProcedure(frenchDoctors);
super.includeNewMembers(frenchDoctors);
}

但这不起作用,因为 Java 编译器认为这是与 DoctorsAssociation::includeNewMembers 不同的方法。 .

我让它工作的唯一方法是进行未经检查的转换:

    @Override
void includeNewMembers(List<? extends Doctor> frenchDoctors) {
@SuppressWarnings("unchecked")
List<FrenchDoctor> frenchFrenchDoctors = (List<FrenchDoctor>) frenchDoctors;
frenchSpecificBureaucraticProcedure(frenchFrenchDoctors);
super.includeNewMembers(frenchDoctors);
}

但我想知道是否有更优雅的方法来做到这一点(即,没有未经检查的转换)。

最佳答案

您可以使 DoctorsAssociation 类通用:

public class DoctorsAssociation<T extends Doctor> {
void includeNewMembers(List<T> doctors) {
// ... do stuff
}
}

然后将您的 FrenchDoctorsAssociation 类声明为

public class FrenchDoctorsAssociation extends DoctorsAssociation<FrenchDoctor> {

@Override
void includeNewMembers(List<FrenchDoctor> frenchDoctors) {
// you now already have List<FrenchDoctor> to work with without casting
}
}

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