我有可同步的接口(interface):
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);
}
并实现该接口(interface)的参数化实例:
public class TstA implements Syncable<TstA> {
@Override
public void sync(TstA other) {
// TODO Auto-generated method stub
}
}
关于java - 声明接口(interface)方法仅允许实现的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22736078/