Java接口和返回类型 [英] Java interfaces and return types

查看:307
本文介绍了Java接口和返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑我有以下接口:

  public interface A {public void b(); } 

然而,我希望实现它的每个类对于方法b具有不同的返回类型()。



示例:

  public class C {
public C b(){}
}

public class D {
public D b(){}
}

我如何定义我的界面以便这是可能的?

解决方案

div>

如果返回类型必须是实现该接口的类的类型,那么您想要的称为 F-bound type

  public interface A< T extends A< T>> {public T b(); } 

public class C implements A< C> {
public C b(){...}
}

public class D implements A< ; D> {
public D b(){...}
}

换句话说, A 声明了一个类型参数 T ,它将取得每个具体类型的值 A 。这通常用于声明类型正确的 clone()或 copy()方法。作为另一个例子,它被 java.lang.Enum 声明每个枚举的继承 compareTo(E)方法仅适用于该特定类型的其他枚举。

如果您经常使用此模式,您将遇到需要 类型的场景 T 。乍一看,很明显它是 1 ,但实际上你需要声明一个抽象T getThis()方法,实现者将会作为评论者指出,有可能做到返回这个

如果 Y ,那么像 X这样的事情会实现A< Y> c>正确合作。 T getThis()方法的存在使得它更加清晰: X 规避了作者的意图 A 界面。


Consider I have the following interface:

public interface A { public void b(); }

However I want each of the classes that implement it to have a different return type for the method b().

Examples:

public class C { 
  public C b() {} 
}

public class D { 
  public D b() {} 
}

How would I define my interface so that this was possible?

解决方案

If the return type must be the type of the class that implements the interface, then what you want is called an F-bounded type:

public interface A<T extends A<T>>{ public T b(); }

public class C implements A<C>{
  public C b() { ... }
}

public class D implements A<D>{
  public D b() { ... }
}

In words, A is declaring a type parameter T that will take on the value of each concrete type that implements A. This is typically used to declare things like clone() or copy() methods that are well-typed. As another example, it's used by java.lang.Enum to declare that each enum's inherited compareTo(E) method applies only to other enums of that particular type.

If you use this pattern often enough, you'll run into scenarios where you need this to be of type T. At first glance it might seem obvious that it is1, but you'll actually need to declare an abstract T getThis() method which implementers will have to trivially implement as return this.

[1] As commenters have pointed out, it is possible to do something sneaky like X implements A<Y> if X and Y cooperate properly. The presence of a T getThis() method makes it even clearer that X is circumventing the intentions of the author of the A interface.

这篇关于Java接口和返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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