+ 2

Java upcasting question

When a subclass is upcasted into it's superclass, does the overriden method and other method not defined in the superclass definition gets removed?

19th Jun 2017, 4:51 PM
Handy
Handy - avatar
2 Réponses
+ 1
Upcasting wonn't change the object itself only your view how you look at it. So, in a way yes you won't be able to see the methods or properties specific to the subclass. However, nothing holds you back from casting back.
20th Jun 2017, 7:09 AM
Kürti Szabolcs
Kürti Szabolcs - avatar
+ 1
Important to note that even if you upcast an object the overriden methods from the subclass will be executed! This is called late binding and it's determined at runtime - it's a very powerfull feature of Java.
20th Jun 2017, 7:15 AM
Kürti Szabolcs
Kürti Szabolcs - avatar