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

Derek Fan
Derek Fan
4,645 Points

Question about exercise2

Dear all, It's Derek. This is my first question, Thanks for your reply in advanced :)

The answer for exercise 2 might be as followed:

my screenshot/ image link

However, I wonder why it cant be the following: I tried but it doesn't work.

my screenshot/ image link

1 Answer

Well, the most immediate reason, as you saw, is that it won't work. You probably got an error message something like this:

incompatible types: BlogPost cannot be converted to String

obj1.getTitle() returns a String, and therefore can be assigned to result, which was declared a String. But more to the point, a String cannot be cast to a BlogPost, which is what result = (BlogPost) obj1.getTitle() is trying to do. In short, first you have to cast the object so it's a BlogPost, and then you can call a BlogPost method on it, viz., getTitle().

Derek Fan
Derek Fan
4,645 Points

Thanks for your clarification, jcorum : )