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 Java Data Structures Getting There Type Casting

2 questions about typecasting and the array Craig created

At about 3:30 in the video, Craig adds (Treet) in front of the someStuff array. Is this because as an object, someStuff doesn't have access to the getDescription() method, and the only way to access the method is to turn it into a Treet?

When the array was declared as an Object[], does that mean the array itself is an object, or is the variable an array of objects?

2 Answers

Alex White
Alex White
16,750 Points

The variable is an Array of Objects

Abhinav Kanoria
Abhinav Kanoria
7,730 Points
  1. Yes, you need to typecast the 'Object' to a 'Treet'. This is because the method getDescription() i=belongs to the 'Treet' class and not the 'Object' class. Object class is the superclass(parent) of 'Treet' class but the method getDescription() belongs specifically to 'Treet' class. That's why you need to typecast it to a 'Treet' object before you can call that method. This is similar to writing : String result = (BlogPost)obj.getTitle(); if you've attempted the task 2 of the challenge just after this video. In the above line of code, you need to typecast 'obj' to 'BlogPost' so that you can call the method getTitle() which belongs to 'BlogPost' class exclusively.

  2. By declaring Object[] someStuff, we are declaring an array of Objects. This means that it can hold objects of different types such as 'Treet', 'String', 'BlogPost', 'PezDispenser', 'Bicycle' and any other real life object that you've created.

Hope this helps!