将派生类传递给需要重写期望基类的方法

2022-01-24 00:00:00 inheritance polymorphism java

我有一个 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.

相关文章