假设我有两个自定义类和一个方法,如下所示:
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)中实现的行为,让 A
和 B
实现该接口(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/