I have the code listed below. Why does it print: "V" - "greet(Z)" - "greet(Z)"? I would have said "V" - "greet(V)" - "greet(Z)" but it seems that I'm missing some points on method overloading and overriding, can someone explain me and/or link some resources to master this?
class Z {
public void me() {
System.out.print(" Z");
}
public void greet(Z z) {
System.out.print ("greet(Z)");
}
}
class V extends Z {
@Override
public void me() {
System.out.println("V");
}
public void greet(V v) {
System.out.println("greet(V)");
}
}
public class Quiz{
public static void main(String[] args) {
Z a = new V();
V b = new V();
a.me();
System.out.print("-");
a.greet(b);
System.out.print("-");
a.greet(a);
}
}
public void greet(V v)
is an overloaded version of public void greet(Z z)
: the former does not override the latter.
a.greet(b);
a
is of type Z
, there is only one method to choose from: greet(Z z)
.
a.greet(a);
a
is of type Z
, there is still only one method to choose from: greet(Z z)
.
b.greet(a);
b
is of type V
, there are two methods to choose from. Since a
is of type Z
, the most appropriate greet(Z z)
will be chosen.
b.greet(b);
b
is of type V
, there are two methods to choose from. Since b
is of type V
, the most appropriate greet(VV)
will be chosen.
When you initialize
V b = new V();
b has a reference of V and object is created of type V so when u call
a.greet(b);
It will first look into V class that is accepting parameter of type V.
But in the first line
Z a = new V();
You are creating object of V but the type is Z.So when calling
a.greet(b);
will only accept the type Z. Because the the greet method in V is overloaded to accept type V.
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.