How does inheritance work (in Java) when casting is involved? Casting works as expected with instance variables but not with methods.
Given the following code; the comments in class C
refers to the resolutions done by the compiler as can be inspected by looking into the bytecode.
class A {
String name;
void test1() {
System.out.println("ATest1 =" + this);
}
void test2() {
System.out.println("ATest2 =" + this);
}
}
class B extends A {
String name;
void test1() {
System.out.println("BTest1 =" + this);
}
void test3() {
System.out.println("BTest3 =" + this);
}
}
class C {
static public void main(String... args) {
B b = new B();
b.name = "Peter"; // Field B.name
((A)b).name = "Petra"; // Field A.name
System.out.println(b.name);
System.out.println(((A)b).name);
b.test1(); // Method B.test1(b)
((A)b).test1(); // Method A.test1(b)
b.test3(); // Method B.test3(b)
b.test2(); // Method B.test2(b)
}
}
You might use casting to set name
in instance b
and to set name
in its accompanying "virtual" object, an instance of class A
, so to speak.
However, if methods are involved the call always resolves to instance b
calling test1
in class B
. This is despite the fact that in ((A)b).test1()
method A.test1(b)
(from a JVM viewpoint) is called.
I don't get the semantics. Can you help?
My guess is that ((A)b).test1()
confirms existence of method test1
in class A
. Nonetheless, class B
is the starting point for method resolution when it comes to invoking the method, because of ((A)b).getClass() ==> class B
. But why is casting "ignored"? Do you have any pointers to the Java Language Specification? I don't know where to look for.