lundi 23 février 2015

Composition class; using super or sub?

Let's consider two classes, super and sup extending super:



Class SuperClass{
int superDataMember;
}

Class SubClass extends SuperClass{
int subDataMember;
}


I need to have another CompositeClass class that may use super or sub composition depending on some criteria. My question is: Should I use




  1. An instance of SuperClass inside CompositeClass



    • Thus, I can use either SuperClass instance or SubClass instance.

    • But how will methods accessing subDataMember behave if the accessed instance is of SuperClass?


    • Maybe an instanceOf check may work at the beginning of each method?



      Class CompositeClass {
      private SuperClass sc;

      public getSuperDataMember () {// some code}
      public getSubDataMember () {
      if (this.sc instanceOf SubClass)
      // some code
      }
      }





  2. An instance of SubClass inside CompositeClass




    • Thus, I will lose the ability to access SuperClass instances!



      Class CompositeClass {
      private SubClass sc;

      public getSuperDataMember () {// some code}
      public getSubDataMember () {// some code
      }
      }





  3. Implement two versions of CompositeClass, the first is SuperCompositeClass with an instance of SuperClass and the second SubCompositeClass that extends the first with an instance of SubClass!




Aucun commentaire:

Enregistrer un commentaire