Search code examples
javastruts2struts

can i change parent class dynamically


Below are my 2 Action classes, which extends different Action classes.

Employee1Action extends HRAction
Employee2Action extends ManagerAction

There is some common code in both Action Classes. I am thinking to copy that common code in another (CommonAction) Action class and Employee1Action and Employee2Action will extends to CommonAction. But both classes have different parent classes. Can i change CommonAction class's parent dynamically ? Means if pointer is in Employee1Action then CommonAction will extends to HRAction and same will be for Employee2Action class.can i do like this ? If yes how can i do it ?


Solution

  • In Java you can't inherit from multiple parent classes- and of course delegation is a more flexible approach than inheritance.

    You may extract an interface with the common operations from Employee1Action and Employee2Action; add an implementation and put the common code into this implementation. Then give to both Employee1Action and Employee2Action objects an instance of your implementation, and have them delegate the common operations to the delegate instance. In this way, you can remove the code duplication.

    In code,

    interface CommonAction {
      void doSomething();
    }
    class DefaulCommonAction implements CommonAction {
      public void doSomething() { 
        /* do something here -
         * this is the duplicate code from Employee 1 and 2 
         */
      }
    }
    
    class HRAction {}
    class ManagerAction {}
    
    class Employee1Action extends HRAction {
      private CommonAction action;
      public Employee1Action (CommonAction action){
        this.action = action;
      }
      // delegate operations
      public void doSomething() {
        action.doSomething();
      }
    }
    class Employee2Action extends ManagerAction {
      // the same delegation here
    }