开发者

Java methods expecting parameters with multiple inheritance

开发者 https://www.devze.com 2023-02-16 16:05 出处:网络
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 th

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

精彩评论

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

关注公众号