title: How To Cast An Inherited Encapsulated Property To Expose Methods Of Subclass - Java
body: <p>In Java I have an abstract base class, let's say <code>WrapX</code>, which contains a property of a type, say <code>X</code> (think Decorator DP). This class presents a method to call a specific method on the encapsulated <code>X</code>:</p>
  
  <pre><code>public abstract class WrapX{
  
    protected X instance;
  
    public WrapX(X x){
       this.instance = x;
    }
  
    public void foo(){
         instance.foo();
    }
  
  }
  
  public class X {
  
     public void foo(){
         System.out.println("foo");
     }
  }
  </code></pre>
  
  <p>There is then a class called <code>Y</code> that extends from <code>X</code> and provides an additional method:</p>
  
  <pre><code>public class Y extends X {
  
    public void bar(){
       System.out.println("bar");
    }
  }
  </code></pre>
  
  <p>Then naturally I have created <code>WrapY</code> that can be used as a decorated type over the type <code>Y</code>:</p>
  
  <pre><code>public class WrapY extends WrapX{
  
    ...
  
    public void bar(){
      instance.bar();
    }
  
  }
  </code></pre>
  
  <p>So herein lies the issue. <code>WrapY</code> has inherited the <code>instance</code> property of type <code>X</code> from its parent <code>WrapX</code>. As far as Eclipse is concerned, <code>instance</code> is of type <code>X</code> and so will complain that it contains no method <code>.bar()</code>. </p>
  
  <p>Fair enough of course, but how then in this subclass can we implicitly cast the <code>instance</code> to an <code>instance</code> of <code>Y</code> (a valid subclass of the initial type <code>X</code>)... WITHOUT the need for explicit cast ascriptions littering the code, or variable shadowing?</p>
  
  <p>If I just had this in the constructor:</p>
  
  <pre><code>public WrapY(Y y){
   this.instance = y;
  }
  </code></pre>
  
  <p>Eclipse still complains that <code>.bar()</code> is not a method of type <code>X</code> because I guess it cannot infer for certain that <code>WrapY(Y y)</code> will be used prior to construct the <code>WrapY</code> instance:</p>
  
  <pre><code>public void bar(){
          instance.bar(); // ERROR
        }
  </code></pre>
  
  <p>Here is the current approach I have, littered with casts:</p>
  
  <pre><code>public WrapY(Y y){
   (Y)instance = y;
  }
  
  public void bar(){
    ((Y)instance).bar();
  }
  </code></pre>
  
  <p>I haven't come across this particular type of architectural problem in my experience before, file it under 'Decorator-Based-Inheritance-Type-Casting'(!)... Please enlighten me as to how I can model this in a better way.</p>
  
  <p>Another issue is that, if in future someone extends <code>WrapY</code>, the type of instance their class inherits will be the natural (uncasted) type of <code>X</code>, when they may reasonably assume it should be of type <code>Y</code>.</p>
  
  <p>Thanks</p>