The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
November 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Overloaded

Posted by Matt Gerrans on November 28, 2001 at 4:09 PM


> I thought that when a class extends a base class it can upcast to the base class type. So WindX would be included as a type InstrumentX. Since it doesnt work without an explicit cast, does this mean that overloading does not work with inheritance?

> > The problem is in the tune method defined in WindError. The tune method takes a parameter of type InstrumentX. Because there is no play method on InstrumentX that takes a NoteX, an error is thrown. An explicit cast is needed on the incoming InstrumentX object to cast it to a WindX object. Then you can call the WindX's play method.

The problem is not that the overloading doesn't work, it is that you are trying to call an overloaded method on a base-class reference, but the base class doesn't define that method.

If you call play() on the WindX object directly, with both the int and the NoteX, you would see the behavior you expect. If you want to use the base class reference, it needs to include that overloaded version of the method, as well, as shown below.

I think part of the confusion you may have had stems from the mix of class names and parameter names. int noteX and NoteX n creates a little mind bender; int n and NoteX noteX would be a little less tricky.

- mfg


// WindSuccess.java

class NoteX
{
public static final int MIDDLE_C = 0, C_SHARP = 1, C_FLAT = 2;
}

class InstrumentX
{
public void play( int noteX )
{
System.out.println("InstrumentX.play( int )");
}

public void play( NoteX n )
{
System.out.println("InstrumentX.play( NoteX )");
}
}

class WindX extends InstrumentX
{
public void play(NoteX n)
{
System.out.println("WindX.play(NoteX n)");
}
}

public class WindSuccess
{
public static void tune(InstrumentX i)
{
i.play( NoteX.MIDDLE_C );
i.play( new NoteX() );
}

public static void main(String[] args)
{
WindX flute = new WindX();
tune(flute);
}
}






Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us