在类的层次结构上与一些子类一起工作。

问题描述 投票:0回答:1

想象一下这个场景。

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
}
java class parent-child hierarchy semantics
1个回答
0
投票

在目前的设置下,这是不可能的,因为不能保证该方法会出现在子类中,除非它是强制的。

现在,你可以做的是,改变父类,并在父类中加入 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的子类。

© www.soinside.com 2019 - 2024. All rights reserved.