I'm writing a Java application, and have a question. How can I implement a function with one parameter which should require an argument which implements multiple interfaces? For example:
interface Father
{
}
interface Teacher
{
}
public void foo(FatherAndTeacher person) // How do I do this?
{
// Do something
}
I know I can use two parameters, such as:
public void foo(Father person1, Teacher person2)
{
// Do something
}
but I think maybe having a single parameter which implements both interfaces would be better.
Two enforce a parameter to have 2 interfaces you have 2 basic options:
Create a common interface that extends both and use that as your parameter type:
interface FatherAndTeacher extends Father, Teacher {
}
The problem with that is that objects that don't implement that interface don't match.
Use generics where you can require matching objects to implement both interfaces:
public <T extends Father & Teacher> void foo(T person) {
// Do something
}
Note that this only works with interfaces, i.e. you can't do T extends Number & String
(2 classes). It works with one object boundary though, in which case the class must be first: T extends ConcretePerson & Father
is ok but T extends Father & ConcretePerson
is not (where ConcretePerson
is a class).
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