Java泛型强制执行抽象方法的返回类型 [英] Java generics to enforce return type of abstract method
本文介绍了Java泛型强制执行抽象方法的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下情况:
abstract class X { abstract X someMethod (...) {...} }.
现在我想约束X的任何实现,让它的'someMethod'方法返回特定的实现类型,而不仅仅是X:
Now I want to constrain any implementation of X to have its 'someMethod' method return that particular implementation type, not just X :
class X1 extends X { X1 someMethod (...) {...} }.
class X1 extends X { X someMethod (...) {...} }. //want this to be flagged as an error
class X2 extends X { X1 someMethod (...) {...} }. //want this to be flagged as an error too
是否可以使用Java泛型实现此目的?
Is it possible to achieve this using Java generics ?
编辑
好的。我只问了是/否问题并得到了是。我的错。我真正感兴趣的是如何编写声明。
Okay. I only asked the yes/no question and got a "yes". My fault. What I was actually interested in is "how do I write the declarations".
推荐答案
这也有效;
abstract class X<T> {
public abstract T yourMethod();
}
class X1 extends X<X1> {
public X1 yourMethod() {
return this;
}
}
class X2 extends X<X2> {
public X2 yourMethod() {
return this;
}
}
这篇关于Java泛型强制执行抽象方法的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文