[英]Interface with a method that requires parameter of implementation type in signature
Here is an example to clarify what I'm meaning: Let's say I have two classes: 这是一个示例,以阐明我的意思:假设我有两个类:
class A {
boolean isEqual(A instance);
}
and 和
class B {
boolean isEqual(B instance);
}
Is there a possibility in Java to define an interface such as Java是否有可能定义一个接口,例如
interface I {
// signature for isEqual(...) here
}
so that the isEqual method in all implementations takes the parameter of the implementation type? 以便所有实现中的isEqual方法都采用实现类型的参数? Like
喜欢
class C implements I {
boolean isEqual(C instance);
}
Thanks in advance! 提前致谢!
I think something like this is what you are looking for: 我认为您正在寻找这样的东西:
interface Equatable<T> {
public boolean isEqual(T instance);
}
class C implements Equatable<C> {
boolean isEqual(C instance);
}
This is similar to the standard Comparable
interface. 这类似于标准的
Comparable
接口。
Is there a possibility in Java to define an interface such as ...
Java是否有可能定义诸如...的接口
Yes, In generic form: 是的,采用通用形式:
public interface I<T> {
public boolean isEqual(T instance);
}
public class C implements I<C> {
@Override
public boolean isEqual(C instance) {
return false;
}
}
Or for example if class A
, B
and C
inherit some super class, lets say DD
. 又例如,如果类
A
, B
和C
继承了某些超类,则可以说DD
。
So you can write: 所以你可以这样写:
interface I {
boolean isEqual(<? extends DD> instance);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.