开发者

Java methods expecting parameters with multiple inheritance

I don't know why I can't find an 开发者_运维百科answer to this online.

I have classes that implement multiple methods and I would like to write methods to expect them. I don't know how to do it though or if it's even possible.

E.g:

public void yellAtPet(<? extends Pet implements YellableAt> arg) {
    arg.yellAt("Don't go there!"); 
    arg.pet("Good Boy");
}


Extends is used for both interfaces and parent classes.

If you want to inforce multiple extends you needs something like:

<T extends ClassA & InterfaceB>

To enforce this on a method, generify the class:

public class MyClass<T extends something & somethingelse>{
    public void doSomething(T arg)
    {
         //call methods defined by either interface
    }
}


This should work fine as a generic method, without making your entire class generic:

public <T extends Pet & YellableAt> void yellAtPet(T arg) {
    arg.yellAt("Don't go there!"); 
    arg.pet("Good Boy");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜