Java method that takes multiple types as one parameter

Suppose I have two custom classes and a method:

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 something like this (just illustrating):

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

Or, in other words, is there a way to write a method with one parameter that takes several types so as not to introduce the processStuff() method several times?

+4
source share
5 answers

Define the behavior you want in the interface, implement the A and B implementation of the interface, and declare processStuff as 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(); } } 
+13
source

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 a parameter type:

 Class C { public void processStuff(Thinker t) { t.think(); } } 
+5
source

Define Thinker as an interface:

 public interface Thinker { public void think(); } 

Then classes A and B implement it:

 public class A implements Thinker 

And finally, define processStuff() to take Thinker as a parameter.

+5
source

You can create a common interface containing the think method, and let A and B implement it.

Or you can overload processStuff() and have two implementations, each of which takes one of the classes.

+1
source

In this case, you can simply use polymorphism. To do this, you overload your methods - create methods with the same name, but with different types of parameters. java does not check method names, it checks method signatures (method name + parameter + return type), for example:

 public class foo { public int add(int a, int b) { int sum = a+b ; return sum ; } public String add(String a, String b) { String sum = a+b ; return sum ; } public static void main(String args[]) { foo f = new foo() ; System.out.printf("%s\n",f.add("alpha","bet)); System.out.printf("%d", f.add(1,2); } } 

this code should return

 alphabet 3 

since you can see that the two method signatures are different, so there is no error. Please note that this is ONLY AN EXAMPLE of what CAN be done.

+1
source

All Articles