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 - Retired Getting There Type Casting

Colby Wise
Colby Wise
3,165 Points

Quick clarification question on up/downcasting + instanceof in code challenge:

I've commented the code below with my understanding/interpretation. My questions are:

  1. Am I correctly thinking about how the logic/code is working (see comment lines)?

  2. What is the purpose of ... (String) obj ... given the if statement (instanceof) has already determined obj is a string. Why doesn't [result = obj] work by itself if obj is a String?

  3. Am I correct in that we are downcasting obj as a BlogPost obj thus giving it BlogPost's properties (i.e. title, description, author, etc) ?

  public static String getTitleFromObject(Object obj) {
    String result = ""; //define string variable result

    if(obj instanceof String){ //test if obj is a string
      result = (String) obj; //if true, set [result] equal to string obj
    } 
    else if(obj instanceof BlogPost) { //test if obj is in BlogPost
 /* DOWNCAST --> ??? */     BlogPost blog = (BlogPost) obj; //if true, cast object as BlogPost
      result = blog.getTitle(); //return [Title] for post object & set return equal to this 
    }
    return result;
  }

1 - Yes - You are defining the variable "result" as a String.

2 - If you put "result = obj" you would be assigning an instance of the String Object to result. By using the "(String) obj" you are assigning a String literal.

3 - Yes - You are assigning it as a BlogPost and not an Object.

http://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal

1 Answer

Colby Wise
Colby Wise
3,165 Points

Many thanks AJ. The stackoverflow link was very helpful