Why java upcasting causes overwritten girl method to be called?

70 views Asked by At

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.

1

There are 1 answers

6
Puce On

The reference variable Mom mom can reference any instance of Mom or instances of subclasses of Mom.

In your case the instance is still a Girl-instance, which is referenced by a Mom reference variable. You have access to any members of Mom (declaration type), but not to the members of Girl. But since the instance is in fact a Girl instance, the implementation of the Girl class will be executed.

This mechanism is called "polymorphism".