Java methods expecting parameters with multiple inheritance

ε祈祈猫儿з 提交于 2019-12-23 19:41:10

问题


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");
}

回答1:


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");
}



回答2:


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
    }
}


来源:https://stackoverflow.com/questions/5304763/java-methods-expecting-parameters-with-multiple-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!