接受多种类型作为单个参数的Java方法 [英] Java method that accepts multiple types as a single parameter

查看:386
本文介绍了接受多种类型作为单个参数的Java方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have two custom classes and a method as follows:

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()(只是说明):

Is there a way to write processStuff()as anything like this (just illustrating):

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

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

Or, in other words, is there a way to write a method with a one parameter that accepts multiple types, as to avoid typing the processStuff() method multiple times?

推荐答案

在接口中定义所需的行为,使AB实现该接口,并声明您的processStuff作为参数接口的实例.

Define the behavior you want in an interface, have A and B implement the interface, and declare your processStuff to take as an argument an instance of the 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方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆