Java接口和返回类型 [英] Java interfaces and return types
问题描述
考虑我有以下接口:
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 $ c $>,那么像
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 parameterT
that will take on the value of each concrete type that implementsA
. This is typically used to declare things likeclone()
orcopy()
methods that are well-typed. As another example, it's used byjava.lang.Enum
to declare that each enum's inheritedcompareTo(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 typeT
. At first glance it might seem obvious that it is1, but you'll actually need to declare anabstract T getThis()
method which implementers will have to trivially implement asreturn this
.[1] As commenters have pointed out, it is possible to do something sneaky like
X implements A<Y>
ifX
andY
cooperate properly. The presence of aT getThis()
method makes it even clearer thatX
is circumventing the intentions of the author of theA
interface.这篇关于Java接口和返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文