假设有2个类别:


Foo(抽象类)
Bar(Foo的孩子)


我希望Foo的抽象函数的参数类型与实现Foo的子类的类型相匹配(这样的类可以是Bar)。

我以为可以使用受约束的泛型类型,但是我不知道如何约束类型以匹配子类。

例:

abstract class Foo {
    public abstract boolean testSth( [Type of the child] obj );
}

class Bar extends Foo {
    @Override
    public boolean testSth( Bar obj ) { // I need the parameter to be of type Bar
        // ...
    }
}

最佳答案

您显然可以将子类型作为通用类型传递给父类:

abstract class Foo<T> {
   // or Foo<T extends Foo<T>>
   public abstract boolean testSth(T obj );
}

class Bar extends Foo<Bar> {
    @Override
     public boolean testSth( Bar obj ) { // I need the parameter to be of type Bar
       // ...
    }
 }

09-17 11:41
查看更多