gpt4 book ai didi

接受多种类型作为单个参数的 Java 方法

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

假设我有两个自定义类和一个方法,如下所示:

class A {
public void think() {
// do stuff
}
}

class B {
public void think() {
// do other stuff
}
}

Class C {
public void processStuff(A thinker) {
thinker.think();
}
}

有没有办法将processStuff()写成这样(只是说明):

public void processStuff({A || B} thinker) {...}

或者,换句话说,是否有一种方法可以编写一个具有接受多种类型的参数的方法,以避免多次键入 processStuff() 方法?

最佳答案

定义您想要在接口(interface)中实现的行为,让 AB 实现该接口(interface),并声明您的 processStuff 作为参数接口(interface)的实例。

interface Thinker {
public void think();
}

class A implements Thinker {
public void think() { . . .}
}

class B implements Thinker {
public void think() { . . .}
}

class C {
public void processStuff(Thinker thinker) {
thinker.think();
}
}

关于接受多种类型作为单个参数的 Java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13978936/

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