简体   繁体   English

通用接口方法和实现类

[英]generic interface method and implementation classes

I have this interface method in the Animal interface : 我在Animal interface有此接口方法:

<T extends Animal> boolean isEqual(T pAnimal);

now I am in trouble with the implementation. 现在我在执行上遇到了麻烦。 I have two classes Dog and Cat . 我有DogCat两个班。 Both classes extends from Animal . 这两个类都从Animal extends而来。 I want to overwrite the method but with the concrete implementation: 我想覆盖该方法,但要具体实现:

@Override
public boolean isEqual(Dog pDog) {
  // do some stuff.
  return true;
}

this leads to the compile error 这导致编译错误

must override or implement a supertype method

How I have to define the interface so that it is not necessary to make a typecast in my concrete implementation class? 我如何定义接口,以便不必在我的具体实现类中进行typecast

Thanks in advance 提前致谢

Stefan 斯特凡

It would work if you move the type parameter to the interface level : 如果将type参数移动到接口级别,它将起作用:

public interface MyInterface<T extends Animal> {
    boolean isEqual(T pAnimal);
}

Then 然后

public class Dog implements MyInterface<Dog> {
    @Override
    boolean isEquals (Dog dog) {}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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