Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...