This code's output is "test of X", but it's expected to be "test of Z".
public class test {
public static void main(String[] args) {
X x = new X();
x = new Z();
x.test(1);
}
}
class Y {
public void test(double a) {
System.out.println("test of Y");
}
}
class X extends Y {
public void test(double b) {
System.out.println("test of X");
}
}
class Z extends X {
public void test(int c) {
System.out.println("test of Z");
}
}
I can't figure out whether it's static binding or dynamic binding. According to Core Java, when this method is called, what happens is following:
- List all the visible methods with the same name as this method, because test in X overrides that in Y, so it should be test in X. Only one candidate.
- Choose the most suitable one according to the type of argument, because test in X in the only candidate, so it must be chosen.
- If this method is private, static, or final then it's static binding. Then resolution is done here. But it's not, so it should be dynamic binding here.
- At the run time, this method is actually called on an object of Z, so it looks up method table of Z, then test in Z should be called.
I don't know what where I take it wrong, the actual output is "test of X".
My OS: Windows 11
My JDK: Java 20