Trying to pass a java test I faced the following question
class A {
int f() { return 1; }
}
class B extends A {
int f() { return 2; }
}
class C extends B {
int f() { return 3; }
int test() {
return super.f() +
((A)this).f();
}
}
Can't figure out why ((A)this).f()
returns 3 but not 1?
This is dynamic dispatch , the static type of the object ( (A)this
, which is A
) does not matter, only the dynamic type , and that is C
.
Similarly, if you do
A a = this;
a.f();
The same value (3) will be returned.
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.