dev*_*ull 6 java generics types
假设我有两个自定义类和一个方法如下:
class A {
public void think() {
// do stuff
}
}
class B {
public void think() {
// do other stuff
}
}
Class C {
public void processStuff(A thinker) {
thinker.think();
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法写processStuff()这样的东西(只是说明):
public void processStuff({A || B} thinker) {...}
Run Code Online (Sandbox Code Playgroud)
或者,换句话说,有没有办法用一个接受多个类型的参数编写一个方法,以避免processStuff()多次输入该方法?
Ted*_*opp 13
在接口中定义所需的行为,拥有A并B实现接口,并声明您processStuff将接口的实例作为参数.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,最简单的是定义一个接口
interface Thinker {
public void think();
}
Run Code Online (Sandbox Code Playgroud)
然后让你的类实现它:
class A implements Thinker {
public void think() {
// do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
并将其用作参数类型:
Class C {
public void processStuff(Thinker t) {
t.think();
}
}
Run Code Online (Sandbox Code Playgroud)
定义Thinker为接口:
public interface Thinker
{
public void think();
}
Run Code Online (Sandbox Code Playgroud)
然后有类A并B实现它:
public class A
implements Thinker
Run Code Online (Sandbox Code Playgroud)
最后,定义processStuff()以a Thinker作为参数.
| 归档时间: |
|
| 查看次数: |
2633 次 |
| 最近记录: |