T
Tony Zuse
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.
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.