Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative of Multiple inheritance in Java

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?

like image 437
Rakesh Juyal Avatar asked Jun 24 '09 13:06

Rakesh Juyal


2 Answers

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();
         }
    }
like image 124
willcodejavaforfood Avatar answered Oct 20 '22 03:10

willcodejavaforfood


use interfaces:

interface InfoMessAware {

     String getMessage();
}

interface BackPageAware {

     String getBackPage();
}

class MyBean implements InfoMessAware, BackPageAware {

     String getMessage() {
         return "message";
     }

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

then replace instanceof with standard method calls.

like image 36
dfa Avatar answered Oct 20 '22 03:10

dfa