title: Composition with different types
body: <p>I have two Java classes B and C in which both extend from class A (I do not own class A).</p>
  
  <pre><code>public class B extends A {…}
  public class C extends A {…}
  </code></pre>
  
  <p>I need a list of type „ListItem“ to hold instances of either B or C, but since both (B and C) are already extended, they cannot be further extended by using „ListItem“ as a superclass. </p>
  
  <p>I think the only way to go is with composition („has-a“ relation…).</p>
  
  <p>Since „ListItem“ should never have B AND C (but only one of them), I am planning to create ListItem with 2 constructors and set an appropriated
  inner type to reflect if either B or C is being hold.</p>
  
  <p>Is there a better approach to accomplish this? Please see the pseudo code below.</p>
  
  <pre><code>public class ListItem {
  
      private enum elemType {
          TYPE_B, TYPE_C 
      } 
  
      private final B mBItem;
      private final C mCItem;
      private final elemType mType;
  
      // used to hold instance of B
      public ListItem(B b) {
          this.mBItem = b;
          this.mType = TYPE_B;
      } 
  
      // used to hold instance of C
      public ListItem(C c) {
          this.mCItem = c;
          this.mType = TYPE_C;
      }
  
      // sample method to demonstrate delegation
      private int getAge() {
          int age;
  
          if (containsB()) {
              age = mBItem.getAge();
          }
          else if (containsC()) {
              age = mCItem.getAge();
          }
          else {…}
          return age;
      }
  
      private boolean containsB() {
          return (mType == TYPE_B);    
      }
  
      private boolean containsC() {
          return (mType == TYPE_C);
      }
  }
  </code></pre>