【问题标题】:Declaring interface method to allow only implemented class声明接口方法只允许实现的类
【发布时间】:2014-05-09 06:53:26
【问题描述】:

我有接口可同步:

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 的实例。

可能我必须使用泛型,但是如何使用?

【问题讨论】:

标签: java generics methods interface restriction


【解决方案1】:

让你的界面通用:

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

【讨论】:

  • 这对我来说足够严格,但不是最终解决方案,因为定义签名: interface Syncable> 并不能推断它会被正确使用,并且可以使用像这样:类 TstA 实现 Syncable
  • @AndreyP 这是可能的。但我想你无法解决这个问题。 :(
  • 是否可以添加限制:类 T1 实现 Syncable 以便 T1=T2 ?
  • @AndreyP 不,你不能那样做。这种限制是不可能的。
  • @AndreyP:如果上述方法对你有用,interface Syncable&lt;T&gt; 也可以。
【解决方案2】:

类似于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&lt;? super T&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 2013-09-23
    • 2015-05-13
    • 2019-03-26
    • 2013-11-13
    相关资源
    最近更新 更多