As already mentioned, casting does not change the object - it passes a "message" to the compiler that in that context it can consider that object to be that class.
But at runtime, the method called is that of the object itself - in the above case, the C.imprimir
. If the called method did not exist in the superclass (that is, if imprimir
was only defined for classes B and C, the compiler would give an error - since it would not be able to generate code to call the imprimir
method of an object of the class A.
Now, regarding your concern for "not understanding some concept of object orientation": be calm - you understood O.O. - casting which is something the Java language borrows from C which is not very "object-oriented", but rather as a mechanism to allow the compiler to find itself in some cases.
If it were in Python for example, another object-oriented language - in Python there is no casting - but you can always call methods in the class itself by passing the instance explicitly - in this case, what you are trying to do would work: / p>
class A:
def i(self):
return "A"
class B(A):
def i(self):
return "B"
b = B()
print(b.i())
print(A.i(b))
It prints output B and A - that is, if the method is called in the instance, as is required in Java syntax, the parameter self
, equivalent to this
, is populated by the language itself - but you have the option to call the method from the class - A.i()
- and in that case has to pass what would be self
explicitly - then it is possible to call superclass methods in subclass instances.
The super
of Java can not give you a direct reference to superclass methods if used outside of subclasses. It exists inside a method, with no arguments, so it assumes it points directly to the object in the superclass, but if you tried to use super
from within Executa
, it would look for the imprimir
method in some superclass of Executa
, and not C
. (Again, super()
of Python allows you to explicitly pass the class and the instance from which you want to access the attributes of the superclass.In the above example, the call below prints A
)
print(super(B, b).i())
The ideal would be a way to convert your objects to the desired class, and the only clean way to do this is to have an explicit method for conversion, which is called in the subclass and returns an object of the desired class.
I found in SOen a similar question, where the answers, including using reflection, indicate that it is not really possible to call a superclass method from an instance of a subclass: link