Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About Java method & a parameter which implements multiple interfaces

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.

like image 519
WaterMoon Avatar asked Oct 18 '25 03:10

WaterMoon


1 Answers

Two enforce a parameter to have 2 interfaces you have 2 basic options:

  1. 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.

  2. 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).

like image 105
Thomas Avatar answered Oct 19 '25 15:10

Thomas