Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

David Pollard
David Pollard
4,324 Points

Java - Typecasting. Counterintuitive that upcasting is always legal ?

Craig mentioned in his excellent video that upcasting an object class is always legal. But, I'm struggling to wrap my head around how that can be ?

A child class may (probably) have certain properties that the parent doesn't. Using the infamous bicycle/mountain bike (parent/child) class analogy. A mountain bike may have a property of seat height.

If it gets upcasted, what happens to seat height, does it just get lost ?

Conversely, downcasting should always be possible as mountain bike would have ALL the properties of its parent "bicycle".

Can anyone help me get my head around why that upcasting is ALWAYS legal, and downcasting isn't. It seems it should be the other way around !?

Thank you

dp

2 Answers

Steven Parker
Steven Parker
231,248 Points

You're right, any specialized properties would get lost. If you need to access them later, you could just temporarily cast the value in an expression but retain the original reference.

On the other hand, casting a "bicycle" as a "mountain bike" could be a problem as it would then be expected to have a "seat height" property and of course it does not.

Does it make more sense now?

David Pollard
David Pollard
4,324 Points

That's brilliant Steven.

Yes, makes perfect sense now, thank you !

:-)

dp