r/javahelp • • 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.

6 Upvotes

32 comments sorted by

View all comments

Show parent comment

1

u/_jetrun Oct 10 '25 edited Oct 10 '25

Then why on mother Earth do I need to do sh*t like — Animal a = new Dog();

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 a should be treated as an Animal and not as a Dog (even though it is a Dog underneath the hood). So if a Dog class has dog-specific methods, you're telling your peers: "for this area of code, those are not important, just operate on a as if it is any kind of Animal and not a Dog specifically".

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 a is an Animal, and I changed Animal a = new Dog() to Animal a = new Cat() - I know it will not break anything because all the code that depends on a treated it as an animal - versus, if I had Dog a = new Dog() - maybe downstream code relies on a.bark() somewhere.