[英]Possible to declare a method in super class that returns an object of type subclass?
I have a class called Calculator, which is extended by many other classes. 我有一个名为Calculator的类,它由许多其他类扩展。 It has a method called intern() which reads as follows: 它有一个名为intern()的方法,其内容如下:
public DailyValueCalculator intern() {
if (TimeSeriesIterator.containsMatchingCalculator(this)) {
TimeSeriesIterator.removeCalculator(this);
return TimeSeriesIterator.getMatchingCalculator(this);
} else {
return this;
}
}
If I have, say, a BetaCalculator called bc, I'd like to be able to intern it by saying 如果我有一个名为bc的BetaCalculator,我希望能够通过说实习它
bc = bc.intern();
Currently though I have to say 目前虽然我不得不说
bc = (BetaCalculator) bc.intern();
Is there any way to make it so that the intern() method would always have a return type of the type on which it was called? 是否有任何方法可以使intern()方法始终具有调用它的类型的返回类型? And if there isn't a way to do this, is there a reason why it's not possible? 如果没有办法做到这一点,有没有理由说不可能?
Possible solutions I'm aware of though am unsatisfied with: 我知道的可能解决方案虽然不满意:
Passing the intern() method a Class and having it return a T (eg 将intern()方法传递给Class并使其返回T(例如
<T extends DailyValueCalculator> T intern(Class<T> returnType){...} <T extends DailyValueCalculator> T intern(Class <T> returnType){...}
Giving DailyValueCalculator a Type <T> (ie making it DailyValueCalculator<T>) that all subclasses would be required to specify where T is equal to the type of the subclass and then having intern() return a T. 给DailyValueCalculator一个Type <T>(即使它成为DailyValueCalculator <T>),所有子类都需要指定T等于子类的类型,然后让intern()返回T.
You can do it if you type your super-class with itself. 如果您自己键入超类,则可以执行此操作。 Here is an example: 这是一个例子:
public abstract class SuperClass<S extends SuperClass<S>> {
public S intern() {
return (S) this;
}
public static class SubClass extends SuperClass<SubClass> {
private void methodOnlyInSubClass() {
System.out.println("subclass method");
}
public void myMethod() {
SubClass sub = intern();
sub.methodOnlyInSubClass();
}
}
}
No there's no way to do this. 不,没有办法做到这一点。 Think about it: I know you know that the intern method is just going to return back the same class, but how could the compiler? 想一想:我知道你知道实习方法只会返回同一个类,但编译器怎么样?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.