OverrideTest.java - Shows Overloaded vs. overridden methods

Download OverrideTest.java

// Code fragments to show when the method invoked is
// over-loaded, instead of overrided.
//
// written 10/2008 by Wayne Pollock, Tampa Florida USA

class Base
{
  public void foo ( int x )
  {
    System.out.println( "foo(int)" );
  }
}

class Derived extends Base
{
  public void foo ( long x )
  {
    System.out.println( "foo(long)" );
  }
}

public class OverrideTest
{
  public static void main ( String [] args )
  {
    Base b = new Derived();
    Derived d = (Derived) b;

    // b.foo( 0L );         // won't compile!
    b.foo( 0 );             // Invokes Base.foo
    ((Derived)b).foo( 0L ); // Invokes Derived.foo
    ((Derived)b).foo( 0 );  // Invokes Base.foo
    d.foo( 0L );            // Invokes Derived.foo
    d.foo( 0 );             // Invokes Base.foo
  }
}

// Experiment with this: try over-riding instead, but change
// Derived.foo to "public"