![](/img/trans.png)
[英]handleEvent method in EventListener interface not implemented in the implementing class
[英]Declaring interface method to allow only implemented class
我有接口Syncable:
public interface Syncable{
public void sync(Syncable other);
}
两个实现的类:
public class TstA implements Syncable{
@Override
public void sync(Syncable other) {
// TODO Auto-generated method stub
}
}
public class TstB implements Syncable{
@Override
public void sync(Syncable other) {
// TODO Auto-generated method stub
}
}
所以这段代码是合法的:
TstA a = new TstA();
TstB b = new TstB();
a.sync(b);
这不是我想要的。 我想允许a.sync接收TstA的实例,b.sync接收TstB的实例。
可能我必须使用泛型,但是怎么样?
使您的界面通用:
public interface Syncable<T extends Syncable<T>> {
public void sync(T other);
}
并实现该接口的参数化实例:
public class TstA implements Syncable<TstA> {
@Override
public void sync(TstA other) {
// TODO Auto-generated method stub
}
}
类似于可Comparable
,这是你如何做到的:
public interface Syncable<T> {
public void sync(T other);
}
public class TstA implements Syncable<TstA> {
@Override
public void sync(TstA other) {
// TODO Auto-generated method stub
}
}
public class TstB implements Syncable<TstB> {
@Override
public void sync(TstB other) {
// TODO Auto-generated method stub
}
}
如果有一个泛型类或方法要求类型参数T
可以同步到自身,那么该类或方法将声明绑定T extends Syncable<? super T>
T extends Syncable<? super T>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.