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?
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();
}
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With