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 类型的参数传递给需要 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.
这篇关于将派生类传递给需要重写期望基类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将派生类传递给需要重写期望基类的方法


- 获取数字的最后一位 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 转换 ldap 日期 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01