[JAVA] Upcast / Downcast

I'm a beginner, but I wrote it for personal study

Upcast

-Storing a subclass instance in a superclass object is called ** upcast ** -Since the compiler will automatically cast if compatibility can be checked, the subclass that is inherited can guarantee all members of the superclass, so the upcast is done ** implicitly **. -If a superclass and a subclass have a field variable or method with the same name, ** the field variable has the superclass and the method has the subclass **.

Downcast

-Conversely to upcast, storing a superclass object in a subclass object is called ** downcast **. ยท A superclass cannot guarantee all members of a subclass, so if you want to downcast from a superclass to a subclass, you need to ** explicitly ** downcast. -If you downcast an object that has not been upcast, you will get a ClassCastException exception. ** You need to upcast once and then downcast ** -It can be determined whether downcasting is possible by comparing whether the object inherits the specified class type or the specified class with the instanceof operator.

Recommended Posts

Upcast / Downcast
Downcast story (memories)