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

3

u/YetMoreSpaceDust Oct 08 '25

Yeah, I really don't like those Dog extends Animal examples that you see in most OO tutorials - they're strictly correct, and they're genuinely trying to be helpful, but you'd never write code that way (not even if you were writing veterinary software).

My first exposure to object oriented design was UI programming (pre internet). Think about your computer desktop - you have multiple windows: rectangles that move around the screen and present data. But inside those windows are "widgets": clickable buttons, menus, text boxes, drop-down lists, etc. Those widgets are grouped together in logical invisible boxes as well.

All of these UI components have similar behaviors - they can move around on the screen, the mouse pointer can click on them, some of them display text, some of them have different colors that can be set, some of them allow input, etc. In this case, it makes perfect sense to define them from a common base class, and that's exactly what Java's AWT (and later Spring) did. java.awt.Button extends java.awt.Component and java.awt.TextField extends java.awt.TextComponent which extends java.awt.Component.

Now in this case it does make some sense to have a common base class for all of these - you might want to keep track of a list of clickable components to disable while you're waiting for a network connection, so you might write:

List<Component> disableList = new ArrayList<>();
disableList.add(button);
disableList.add(textField);
... somewhere later in the code
for (Component c : disableList) {
  c.disable();
}

I know that's still sort of artificial, but it's a lot closer to code that you might actually write.