2019-07-31
Alternative of Multiple inheritance in Java
stackoverflow
Question

I have created two beans

class BackPageBean{
   String backPage = null;
  :
  :
  :
}


class InformationMessageBean{
   String informationMessage = null;
  :
  :
  :
}

Now, if a class is backpage aware then it will extend backPageBean, or if it need to show some kind of message then it extends InformationMessageBean.

class BackPageAware extends backPageBean{
}

class InfoMessAware extends InformationMessageBean{
}



    someFunction () {
       if ( theObject instanceOf backPageBean ) {
              prepareTheBackPage ( theObject.getBackPage() );
       }

       if ( theObject instanceOf InformationMessageBean ) {
              showtheInformation ( theObject.getMessage() );
       }

   }

Now the problem is, if i want to have a bean which is both BackPageAware as well as InformationAware then, as we don't have multiple inheritance, what should be the approach?

Answer
1

Just to clarify my comment.

Just like Darth Eru says you create the two interfaces and the two default implementations. When you have a bean that needs both of the behaviours you have that class implement the two interfaces but you also create variables of the default implementations. This way you still dont need to duplicate any code.

    interface InfoMessAware {

         String getMessage();
    }

    interface BackPageAware {

         String getBackPage();
    }

class DefaultInfoMessAware {
         String getMessage() {
             return "message";
         }
}

class DefaultBackPageAware {
         String getBackPage() {
             return "backPage";
         }
}

    class MyBean implements InfoMessAware, BackPageAware {
         private InfoMessAware messAware = new DefaultInfoMessAware();
         private BackPageAware backPageAware = new DefaultBackPageAware();

         String getMessage() {
             return messAware.getMessage();
         }

         String getBackPage() {
             return backPageAware.getBackPage();
         }
    }
Alternative of Multiple inheritance in Java
See more ...