想象一下这个场景:
public class A {
...
}
class B extends A {
public foo getFoo() {
returns _foo;
}
}
there also exist other classes children of A having the same method
class C extends A {
...
public foo getFoo() { returns _foo; }
...
}
So, the method `foo` doesn't exist in parent class, however, it exists in all children classes.
Is there a way in Java to not directly specify which child class will be called however use a generic way (I believe in Scala it's [T < A]).
So that I can use it like this:
void Bar(`[some child class of A]` childOfA){
childOfA.getFoo(); // Now this would return either getFoo() of A or B
}
最佳答案
这在当前设置中是不可能的,因为除非强制要求,否则无法保证该方法将出现在子类中。
现在,你可以做什么,更改父类,并添加 abstract
方法那里。这将确保该方法始终存在于子类或其进一步的子类中(如果子类是抽象的)。
abstract class A {
public abstract Foo getFoo();
}
class C extends A {
public Foo getFoo(){
// your code
}
}
现在,您可以为通用方法设置上限。
void <T extends A> bar(T childOfA){
childOfA.getFoo();
}
在这里,<T extends A>
将确保你的论点应该是 A 的子类。
关于java - 使用类层次结构中的某些子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61973085/