Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method that accepts multiple types as a single parameter

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();
  }
}

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

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

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?

like image 326
devnull Avatar asked Dec 20 '12 19:12

devnull


2 Answers

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();
    }
}
like image 168
Ted Hopp Avatar answered Nov 15 '22 08:11

Ted Hopp


In this case, the simplest is to define an interface

interface Thinker {
   public void think();
}

then let your classes implement it :

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

and use it as parameter type :

Class C {
  public void processStuff(Thinker t) {
    t.think();
  }
}
like image 30
Denys Séguret Avatar answered Nov 15 '22 08:11

Denys Séguret