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

Diego Marrs
Diego Marrs
8,243 Points

Not sure what the 2nd challenge is asking me to do...

So the description:

Now make sure that if a com.example.BlogPost is passed in for obj that you can cast it to a BlogPost. Return the results of the getTitle method on the newly type-casted BlogPost instance.

I am very confused what most of this means and what it is telling me to do.

Please Help!

2 Answers

The challenge asks to check for the types of the Object instance (obj) specified and type-cast accordingly. Here is what the challenge expects us to do:

  public static String getTitleFromObject(Object obj) {
    // Fix this result variable to be the correct string.
    String result = "";
    // Check if obj is of type 'String' and type-cast to String type if it indeed is.
    if(obj instanceof String) {
      result = (String) obj;
    // Otherwise, check if obj is of type 'BlogPost'
    // and invoke the getTitle() method after type-casting.
    else if(obj instanceof BlogPost){
      BlogPost blogPost = (BlogPost) obj;
      result = blogPost.getTitle();
    return result;
Diego Marrs
Diego Marrs
8,243 Points

Thanks! But..."else if"? I'm not sure we ever covered that, why not just use "else" instead?

If we use "else" instead of "else if (...)", then when an object of any type other than "String" (not only "BlogPost", but also any other type) is passed, then the method will try to type cast it BlogPost which may result in a ClassCastException (if obj is not of type 'BlogPost'). So, we need to ensure that the obj specified is indeed of type 'BlogPost' and hence the conditional check with "else if(...)".