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

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

问题描述

考虑我有以下界面:

public interface A { public void b();}

但是,我希望实现它的每个类都对方法 b() 具有不同的返回类型.

示例:

公共类 C {公共 C b() {}}公共类 D {公共 D b() {}}

我将如何定义我的界面才能实现这一点?

解决方案

如果返回类型必须是实现接口的类的类型,那么你想要的就叫做F 有界类型:

public interface A<T extends A<T>>{ public T b();}公共类 C 实现了 A<C>{公共 C b() { ... }}公共类 D 实现 A<D>{公共 D b() { ... }}

换句话说,A 声明了一个类型参数 T,它将采用实现 A 的每个具体类型的值.这通常用于声明诸如 clone()copy() 等类型良好的方法.作为另一个例子,它被 java.lang 使用.Enum 声明每个枚举继承的 compareTo(E) 方法仅适用于该特定类型的其他枚举.

如果您经常使用这种模式,您会遇到需要 thisT 类型的场景.乍一看似乎很明显它是1,但实际上您需要声明一个abstract T getThis() 方法,实现者必须简单地将其实现为<代码>返回这个.

[1] 正如评论者所指出的,如果 XY> 适当合作.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天全站免登陆