Reputation: 463
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?
Upvotes: 6
Views: 5985
Reputation: 1750
In this case you could simply use Polymorphism. To do this you overload your methods-- create methods that have the same name, but different parameter types. java does not check method names, it checks method signatures(a methods 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
as you can see the two method signatures are different, so there is no error. please note this is JUST an EXAMPLE of what COULD be done.
Upvotes: 1
Reputation: 1663
Define Thinker
as an interface:
public interface Thinker
{
public void think();
}
Then have classes A
and B
implement it:
public class A
implements Thinker
And finally, define processStuff()
to take a Thinker
as a parameter.
Upvotes: 5
Reputation: 7157
You could make a common interface containing the think
method, and let A
and B
implement it.
Or you could overload processStuff()
and have two implementations, each taking one of the classes.
Upvotes: 1
Reputation: 382150
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();
}
}
Upvotes: 5
Reputation: 234795
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();
}
}
Upvotes: 15