Why is the final output "WuffRingding" instead of "RingdingRingding"?
package ubung;
class Hund{
public Hund(){
}
public String bellen(){
return "Wuff";
}
public String spielen(Hund h){
return "Wuff" + h.bellen();
}
}
class Fuchs extends Hund{
public Fuchs(){
}
public String bellen(){
return "Ringding";
}
public String spielen(Fuchs f){
return "Ringding"+ f.bellen();
}
}
public class park {
public static void main(String[] args){
Hund bello = new Hund();
Fuchs foxi = new Fuchs();
Hund hybrid = new Fuchs();
System.out.println(hybrid.spielen(foxi));
}
}
Why is the final output "WuffRingding" instead of "RingdingRingding"? Why is the final output "WuffRingding" instead of "RingdingRingding"?
The output is WuffRingding
since the method public String spielen(Hund h)
is overloaded in the child class Fuchs
to public String spielen(Fuchs f)
. Java calls the method of the type and not of the actual instance when a method is overloaded.
So the type used here is Hund
for the hybrid
variable and since the method to be called is decided at compile time for overloaded methods the overloaded method of the Hund
class is invoked althogh it is pointing to the Fuchs
instance.
Now you supplied a instance of Fuchs
as a parameter to the spielen(Hund h)
which clearly takes the type Hund
as a parameter, this worked as Hund
is a parent of Fuchs
and can hold Fuchs
reference, this combined with runtime/dynamic polymorphism the bellen
method of the Fuchs
class is called instead of Hund
as at runtime the type of the instance is inspected and it was actually pointing to an instance of Fuchs
.
TLDR;
spielen
on a Hund
reference, calls spielen
of Hund
class as it is overloaded.Fuchs
so at runtime the method bellen
of Fuchs
is called instead of Hund
due to dynamic method dispatch / runtime polymorphism .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.