I have come across a weird piece of code. I was wondering if there is any usage for it.
class C extends B {
int xB = 4;
C() {
System.out.println(this.xB);
System.out.println(super.xB);
System.out.println(((B)this).xB); // This is the weird code.
}
}
Program prints 4, 10, 10. public xB field of class B has the value 10.
In Java, you can only directly inherit from a single class. But you can have multiple indirect superclasses. Could this be used in upcasting the "this" reference to one of those? Or is this bad programming practice and i should forget about it?
So "((B)this)" basically acts as if it is "super". We could just use super instead of it.
It does NOT generally do the same thing as super
.
It does in this case, because fields do not have dynamic dispatch. They are resolved by their compile-time type. And you changed that with the cast.
But super.method()
and ((SuperClass)this).method()
are not the same. Methods are dispatched at runtime based on the actual type of the instance. The type-cast does not affect this at all.
I was wondering if people are using this structure to upcast "this" to indirect superclasses.
They don't have to, because they don't duplicate field names like that.
It is bad practice to shadow an inherited (visible) field in a subclass (exactly because it leads to confusion like this). So don't do that, and you want have to have this cast.
And you cannot "upcast to indirect superclasses" at all where methods are concerned: You can call super.method()
directly (if you are in the subclass), but not something like super.super.method()
.