简体   繁体   中英

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.

You can use a composite interface by extending both of your Teacher and Father interfaces.

Here's an example:

interface Teacher
{
    void teach();
}

interface Father
{
    void makeBadJoke();
}

// ----- Composite interface! Doesn't add any methods.
interface TeacherAndFather extends Teacher, Father
{
    /*This can be empty*/
}

class Bob implements TeacherAndFather
{
    public void teach() { System.out.println("1 + 1 = 2"); }
    public void makeBadJoke() { System.out.println("Knock knock..."); } 
}

class Main
{
    private static void foo(TeacherAndFather foo)
    {
        foo.teach();
        foo.makeBadJoke();
    }

    public static void main (String... args)
    {
        foo(new Bob());
    }
}

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, ie 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).

just use Object as your function parameter type:

void doSomething(Object param);

or using generic method:

<T> void doSomething(T param);

or let the two interface both inherit from one same interface.

public interface Person {}
public interface Teacher extends Person {}
public interface Father extends Person {}
public class Test {
    public void foo(Person p) {
        //
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM