What is the difference between Upcasting and Downcasting, and what are the risks of the latter?
Last updated
Upcasting (derived to base) is implicit and always safe. You lose access to subclass-only members, but virtual methods still dispatch to the real type.
Downcasting (base to derived) is explicit and fails at runtime if the object isn't really that subtype (
ClassCastException/InvalidCastException). Frequent downcasting often signals polymorphism should be used instead.Guard downcasts with a type check (
instanceof,is, pattern matching) or useas, which returns null instead of throwing.
- https://www.reddit.com/r/developersIndia/comments/1ktgmfk/software_development_interview_preparation/
- https://www.reddit.com/r/programming/comments/1m2ff3j/casey_muratori_the_big_oops_anatomy_of_a/
- https://www.reddit.com/r/SoftwareEngineering/comments/1ijqgpb/is_the_o_in_solid_still_relevant_or_just_a_relic/
- https://www.reddit.com/r/NorthropGrumman/comments/1bt1ug3/monthly_employmentcorporate_questions_and/