Here is the code I wrote:
https://pastebin.com/raw/0iBrGJR4
Most relevant parts:
A a = new A();
B b = new B();
System.out.println(((A) b).a());
System.out.println(((A) b).b(3));
static class A {
Object a() {
System.out.println("A.a()");
}
Object b(Number x) {
System.out.println("A.b()");
}
}
static class B extends A {
String a() {
System.out.println("B.a()");
return "hello";
}
String b(Integer x) {
System.out.println("B.b()");
return "hola" + x;
}
}
When I run this, the first print displays
B.a()
hello
which is what I expected, since even though we cast to A, the call goes through to the object's actual type which is B.
But the second print, the ((A) b).b(3) call, prints
A.b()
3
(i.e. it calls the method in A). Force casting 3 to Integer doesn't do anything either. Can someone explain this behavior to me? I don't understand what the reason is. I would've expected ((A) b).b(3) to print B.() \n hola3 rather than use the parent class method.