Why does this code output "A-h" instead of "B-h"?
class A {
public void f(){ System.out.println("A-f"); }
public static void g() { System.out.println("A-g"); }
public void h(A x){ System.out.println("A-h"); }
}
class B extends A {
public void f() { System.out.println("B-f"); }
public static void g() { System.out.println("B-g"); }
public void h(B x){ System.out.println("B-h"); }
}
public class Sample5 {
public static void main(String[] args) {
B x = new B();
A y = x;
y.h(x);
} }
Here's what my thought process. At compile time, it checks in the declared type A if there is a function that matches the signature, and because x is of type B, a subtype of A, then there is no compile error. Then at runtime, it will look in the object it is referring to. It refers to object x, and then it looks in B for the method, and it finds B's h(x). That's why I keep getting "B-h".
Does anyone know what I'm missing? I followed these rules for every other example and got it correct, except for this one.
If anyone can help at all, it'd be greatly appreciated!
class A {
public void f(){ System.out.println("A-f"); }
public static void g() { System.out.println("A-g"); }
public void h(A x){ System.out.println("A-h"); }
}
class B extends A {
public void f() { System.out.println("B-f"); }
public static void g() { System.out.println("B-g"); }
public void h(B x){ System.out.println("B-h"); }
}
public class Sample5 {
public static void main(String[] args) {
B x = new B();
A y = x;
y.h(x);
} }
Here's what my thought process. At compile time, it checks in the declared type A if there is a function that matches the signature, and because x is of type B, a subtype of A, then there is no compile error. Then at runtime, it will look in the object it is referring to. It refers to object x, and then it looks in B for the method, and it finds B's h(x). That's why I keep getting "B-h".
Does anyone know what I'm missing? I followed these rules for every other example and got it correct, except for this one.
If anyone can help at all, it'd be greatly appreciated!