[英]How to use abstract class' child type as the type of an abstract method's parameter?
假設有 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
// ...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.