如何使接口实例方法只接受同一类的参数? [英] How can I make an interface instance method accept arguments of the same class only?

查看:115
本文介绍了如何使接口实例方法只接受同一类的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用这样的界面:

  public interface ResultItem {
public int getConfidence();
public boolean equals(ResultItem item);
public ResultItem cloneWithConfidence(int newConfidence);
}

我通过不同种类的表示语音识别结果的对象来实现。 / p>

想法是,我只想比较同样的结果。也就是说,如果我创建一个类 IntResult 实现 ResultItem ,我希望方法签名成为:

  public boolean equals(IntResult item); 
public IntResult cloneWithConfidence(int newConfidence);

我觉得我的界面有一个设计缺陷,因为现在我使用了很丑的关于cloneWithConfidence的结果和其他返回ResultItem的方法。



有更好的方法吗?

解决方案

有一个常见的成语如下:

  public interface ResultItem< T扩展ResultItem< T>> {
public int getConfidence();
public boolean equals(T item);
public T cloneWithConfidence(int newConfidence);
}

public class IntResult实现ResultItem&IntResult> {
// ...
}


I want to use an interface like this :

public interface ResultItem {
    public int getConfidence();
    public boolean equals(ResultItem item);
    public ResultItem cloneWithConfidence(int newConfidence);
}

I have it implemented by different kind of objects representing a voice recognition result.

The idea is, I wish to compare only results of the same kind. That is, if I create a class IntResult implementing ResultItem, I want that the method signatures become :

public boolean equals(IntResult item);
public IntResult cloneWithConfidence(int newConfidence);

I feel that there is a design flaw in my interface, because for now I am using pretty ugly casts on the results of cloneWithConfidence and of other methods returning a ResultItem.

Is there a better way?

解决方案

There is a frequently-seen idiom that goes as follows:

public interface ResultItem<T extends ResultItem<T>> {
    public int getConfidence();
    public boolean equals(T item);
    public T cloneWithConfidence(int newConfidence);
}

public class IntResult implements ResultItem<IntResult> {
  //...
}

这篇关于如何使接口实例方法只接受同一类的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆