Re: mysterious overriding behavior



In the latter case you are not overriding the method. By narrowing the type
in X::speak(Y y) you eliminated the signature X::speak(X x) and introduced
a similar signature that exists only in Y [Y:speak(X x)].

What I do find odd is that if I override X::speak(Y y) in Y the compiler is
happy and lets you make the call, later if you take out the override *and
compile only the Y class and not the test driver* the VM runs as expected.

Try this in your second case.
class Y extends X{

void speak(X x){
System.out.println("Y");
}

void speak(Y y)
{
System.out.println("YY");

}
}

Once "Testing" compiles against this you can yank out the second method,
compile Y and run the test with the call going to X:speak(Y y);

FYI jdk1.4.1_02 for all.

My head hurts now.




On Wed, 13 Dec 2006, Tony Zuse wrote:

Hello everyone,

I always thought the method called depended on the type of the object,
so when I define superclass X and its subclass Y:

class X{
void speak(){
System.out.println("X");
}
}
class Y extends X{
void speak(){
System.out.println("Y");
}
}

Testing yields:

public class Testing{
public static void main(String[] args){
X x=new X();
X xy=new Y();
Y y=new Y();
x.speak(); //prints "X"
xy.speak(); //prints "Y"
y.speak(); //prints "Y"
}
}
... as expected. However, if I add parameters to the functions:

class X{
void speak(Y y){
System.out.println("X");
}
}
class Y extends X{
void speak(X x){
System.out.println("Y");
}
}

I get a compile time error from xy.speak(x) whereas xy.speak(y) prints
"X", which effectively means java calls the reference-speak and not the
type-speak.

Can anybody explain to me what's happening here?

Thanks, Tony.



.



Relevant Pages

  • virtual and override using inheritance
    ... class called Cat. ... If I compile the program as it is now I get the following ... the current member override that implementation, ... public virtual void MyTest() ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: mysterious overriding behavior
    ... What I do find odd is that if I override X::speakin Y the compiler ... compile only the Y class and not the test driver* the VM runs as expected. ... void speak{ ... Once "Testing" compiles against this you can yank out the second method, ...
    (comp.lang.java.programmer)
  • Re: Partially overriding a method?
    ... It will help you see that a method either does or does not override another. ... public static void main{ ... class SubClass extends MainClass { ... DoesItOverride doesIt = new Rider; ...
    (comp.lang.java.programmer)
  • Re: menu-based console application
    ... typedef void; ... struct MenuEntry ... Compile everything, fix typing errors and run the program. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: CFile and FILE*
    ... ever call exit() in any C++ ... LPVOID, e.g., ... void DoSomething ... Note that you can still compile this as C ...
    (microsoft.public.vc.mfc)