java - 使用类层次结构中的某些子类

标签 java oop generics inheritance

想象一下这个场景:

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/

相关文章:

java - Java Generic Type 参数可以扩展另一个 Type 参数和附加的有界类型吗?

java - Java (Android) 中的 List<?> 是什么?

java - 获取通用数组的大小

java - 让单个 Java 注解隐式设置多个注解

java - 在单独的类中使用 Java native 方法时出现 UnsatisfiedLinkError

java - 如何从存储过程返回多行?

Java 客户端/服务器聊天应用程序

java - 关于对单个字符串使用域对象的意见

c# - "private"和 "protected Internal"有什么区别?

c++ - 内部阶层的可及性