r/javahelp • u/Nobody37373 • Oct 08 '25
Unsolved Why learn Upcasting/Downcasting?
After days of getting stuck in this concept, i finally feel like giving up and never looking at it back again. After countless hours of Googling, asking assistance from AI, watching YouTube videos, I am now falling into a guilt of why I am even wasting time over a single concept. I feel I should move on at this point. Before this one topic, one google search used to clear all my doubts so effortlessly guys.
But this one seems like a tough nut to crack. Can anyone help me out on this?
I know the 'how' and 'what', but I am not reaching anywhere near to the 'why' of this one concept.
View all comments
Show parent comment
1
u/_jetrun Oct 10 '25 edited Oct 10 '25
Software Engineering is a social and collaborative activity. Sometimes you do things to communicate intent to your present or future peers that work on your code.
I would place this specific example in that category. You are communicating to the system and your peers that
ashould be treated as anAnimaland not as aDog(even though it is aDogunderneath the hood). So if aDogclass has dog-specific methods, you're telling your peers: "for this area of code, those are not important, just operate onaas if it is any kind ofAnimaland not aDogspecifically".This pattern comes up often in the initializations of collections, for example:
List<String> list1 = new ArrayList<>();or
List<String> list1 = new LinkedList<>();You are communicating to the system, and your peers that list1 should be treated as a List type and not explicitly as an 'ArrayList' or 'LinkedList'.
One of the benefits of this, it makes it easy to swap out the 'type' of Animal later on without making any other code changes. If I know
ais an Animal, and I changedAnimal a = new Dog()toAnimal a = new Cat()- I know it will not break anything because all the code that depends onatreated it as an animal - versus, if I hadDog a = new Dog()- maybe downstream code relies ona.bark()somewhere.