Java Java Data Structures Getting There Type Casting

Christian Thieme
Christian Thieme
9,448 Points

Why is he adding the (Treet) before the code in this - ((Treet) someStuff[0]).getDescription();

I don't understand why he is adding the (Treet) before the code in this - ((Treet) someStuff[0]).getDescription();

I get all the code after the Treet, but don't understand why he added that at the beginning.

This is not the best treehouse video i've ever seen. This one could be revamped.

1 Answer

Seth Kroger
Seth Kroger
56,369 Points

In this video, someStuff is an array of Objects. Because each item in the array is treated like an Object, and Objects don't have a getDescription method like Treet does, the item needs to be cast to a Treet to access it. It's equivalent to:

Treet aTreet = (Treet) someStuff[0];
aTreet.getDescrption();

It's just compressed into one line, and the extra parentheses are there to make the order of operations correct (to cast the item from the array, not the result of getDescription()).