gpt4 book ai didi

java - 如何用java中的接口(interface)覆盖方法

转载 作者:行者123 更新时间:2023-12-03 20:56:01 25 4
gpt4 key购买 nike

我有一个接口(interface) I,两个实现它的类 A 和 B 以及一个具有通用类型接口(interface) I 的列表,因此它可以包含类型 A 和 B 的两个对象。

class A implements I
class B implements I
List<I> myList

我想(在一个单独的类中)编写两个方法 process( A a ) 和 process( B b ) 这样我就可以遍历列表并为每个元素调用 process( i ) 和 java 将自动 (unbox? ) 对象并调用正确的方法。

class D{
processList(){
for( I i : myList ){
process( i ); // invoke either process(A) or process(B) based on instanceof
}
}
public void process(A a){...}
public void process(B b){...}
}

我知道我可以通过在列表中的每个元素上调用“instanceof”然后 if-else 来调用不同的方法来做到这一点,但必须有更好的方法。

在MVC场景下,A类和B类在Model中,D类在Controller中,需要分离。

有人能帮忙吗?

最佳答案

there must be a better way.

有。将方法 process() 添加到接口(interface) I .然后你可以调用process在迭代 List<I> 时在项目上-

List<I> list = new ArrayList<>(); 
// populate list with A and B instances, then
for (I i : list) {
i.process();
}

显然 AB然后必须提供 process() 的具体实现.

关于java - 如何用java中的接口(interface)覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25452073/

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