gpt4 book ai didi

java - 接口(interface)参数类型的继承

转载 作者:行者123 更新时间:2023-11-29 09:55:51 25 4
gpt4 key购买 nike

我正在尝试将请求的基本实现作为接口(interface)函数的参数类型。

然后让各种类扩展基本请求类以赋予请求对象更具体的含义。

但 Java 需要确切的类作为参数,并且不支持由该基类扩展的类。

public interface MyInterface{
public String getValue(BaseRequest req);
}

public class MyInterfaceImpl implements MyInterface{
public String getValue(SpecificRequest req){ //Java will give a compile error here.
//Impl
}
}

public interface BaseRequest{
int requiredA;
int requiredB;
//setter and getters for A and B
}

public class SpecificRequest extends BaseRequest{
int specificValC;
//setter and getters for C
}

实现此模式的最佳方法是什么?还是我设计得太多了?

最佳答案

您可以使用泛型实现类似的效果。

public interface MyInterface<R extends BaseRequest> {
public String getValue(R req);
}

public class MyInterfaceImpl implements MyInterface<SpecificRequest> {
public String getValue(SpecificRequest req){
//Impl
}
}

关于java - 接口(interface)参数类型的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11993657/

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