将派生类传递给需要覆盖期望基类的方法 [英] Passing Derived Class to a method which needs to override expecting a base class
问题描述
我有一个类A,抽象方法doAction(BaseClass obj)期望一个类型为BaseClass的参数
I have a class A, with an abstract method doAction(BaseClass obj) expecting a param of type BaseClass
public class A {
//....
abstract void doAction(BaseClass obj);
//....
}
现在,我有另一个班级B需要扩展A.但是,B的doAction方法需要使用扩展BaseClass的对象DerivedClass。
Now, I have another class B which needs to extend A. However, B's doAction method needs to use an object DerivedClass which extends BaseClass.
public class B extends class A {
//..
void doAction(DerivedClass obj) {
obj.callMethodAvailableOnlyInDerivedClass();
}
}
我如何处理这种情况我需要将类型为DerivedClass的param传递给要覆盖的方法,同时期望一个BaseClass?
How do I handle this situation where I need to pass param of type DerivedClass to the method to be overridden while it is expecting a BaseClass ?
谢谢!
推荐答案
您使基类具有通用性:
public class A<T extends BaseClass> {
//....
abstract void doAction(T obj);
//....
}
以及参数化的子类派生类:
and the subclass parameterized with the derived class:
public class B extends A<DerivedClass> {
//..
void doAction(DerivedClass obj) {
obj.callMethodAvailableOnlyInDerivedClass();
}
}
没有泛型,这是不可能的,因为B会打破A:A的契约接受任何类型的BaseClass,但是您将B限制为仅接受特定的子类。这不尊重 Liskov原则。
Without generics, it's not possible because B would break the contract of A: A accepts any kind of BaseClass, but you retrict B to only accept a specific subclass. This does not respect the Liskov principle.
这篇关于将派生类传递给需要覆盖期望基类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!