title: Method overloading using derived types as parameters in Java
body: <p>Let's say I have existing code which I want to extend but also to avoid changing it as much as possible. </p>
  
  <p>Somewhere around this code there is a method that receives some type.</p>
  
  <pre><code>Engine.method(Base b) 
  </code></pre>
  
  <p>Now, I want to extend this functionality. So I extends Base into a type called Derived which holds some more data I need and I also implements another method that receives the Derived type and do something different with it. </p>
  
  <pre><code>Engine.method(Derived d)
  </code></pre>
  
  <p>But I don't want to change the original call to "method". I somehow managed to instansiate the correct type (Base or Derived) by using a flag but since the original call is taking the Base then my new method will not be called.</p>
  
  <pre><code>Base b = null;
  if(flag) {
     b = new Derived()
  } else{
     b = new Base()
  } 
  Engine.method(b) 
  </code></pre>
  
  <p>The problem is that now my Engine.method(Derived d) will not be called. I worked-around it by using casting </p>
  
  <pre><code>if(flag)
  Engine.method((Derived)b) 
  </code></pre>
  
  <p>But that's wrong and stupid. Any suggestions?</p>
  
  <p>I can always do: </p>
  
  <pre><code>if(flag) {
     Engine.methodForBase(new Base())
  } else{
     Engine.methodForDerived(new Derived())
  } 
  </code></pre>
  
  <p>But can you think of something better? </p>
  
  <p>Thanks</p>