Re: mysterious overriding behavior
- From: Timothy Bendfelt <bendfelt@xxxxxxxxxxx>
- Date: Wed, 13 Dec 2006 18:22:47 -0600
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.
.
- Follow-Ups:
- Re: mysterious overriding behavior
- From: Tony Zuse
- Re: mysterious overriding behavior
- From: Mike Schilling
- Re: mysterious overriding behavior
- References:
- mysterious overriding behavior
- From: Tony Zuse
- mysterious overriding behavior
- Prev by Date: Re: Getting class to compile under JDK 1.5 AND 1.6
- Next by Date: Re: Is a Java Application much faster than an Applet.
- Previous by thread: mysterious overriding behavior
- Next by thread: Re: mysterious overriding behavior
- Index(es):
Relevant Pages
|