更新时间:2021-10-05 08:56:51
您可以通过指定类型可以是 Something
或其子类之一来使 A 类泛型(我已经将setSomething
方法抽象,但您可以根据需要提供实现).
You can make the A class generic by specifying that the type can be Something
or one of its subclasses (I've made the setSomething
method abstract but you can provide an implementation if you want).
abstract class A <T extends Something> {
public abstract void setSomething(T something);
}
然后强制类型 T 成为您想要在子类中使用的特定类.
Then force the type T to be the specific class you want in your subclasses.
class B extends A<FirstSomething> {
@Override
public void setSomething(FirstSomething something) {
//Set the something
}
}
class C extends A<SecondSomething> {
@Override
public void setSomething(SecondSomething something) {
//Set the something
}
}