I’m trying to understand upcasting with Java. I just created two classes Mom and Girl, with each having their own constructor (constructors have no parameters).
If I understand, Mom mom = new Girl() causes the instance created by new Girl to be cast to a Mom type, and that is confirmed by the fact that the Mom constructor is being called. So mom variable is pointing to a Mom instance, right? So, why, when I overwrite a Mom method test() in the Girl class, it causes the Girl method test() to be called instead of the Mom method? It's just so confusing: on one side Mom constructor is being called on the other side, the Girl method is called, like if mom variable has access to both classes.
The reference variable
Mom momcan reference any instance ofMomor instances of subclasses ofMom.In your case the instance is still a
Girl-instance, which is referenced by aMomreference variable. You have access to any members ofMom(declaration type), but not to the members ofGirl. But since the instance is in fact a Girl instance, the implementation of theGirlclass will be executed.This mechanism is called "polymorphism".