Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Derived Class to a method which needs to override expecting a base class

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);
    //....
}

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();
      }

 }

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 ?

Thanks!

like image 784
Skynet Avatar asked Feb 23 '12 21:02

Skynet


2 Answers

You make the base class generic:

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();
     }
}

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.

like image 176
JB Nizet Avatar answered Sep 21 '22 03:09

JB Nizet


You can use:

public abstract class A<T extends BaseClass> {
//....
abstract void doAction(T obj);
//....
}


public class B extends class A<DerivedClass> {
 //..
 void doAction(DerivedClass obj) {
      obj.callMethodAvailableOnlyInDerivedClass();
  }

}
like image 23
Puce Avatar answered Sep 19 '22 03:09

Puce