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

Matthew Burkett
Matthew Burkett
3,488 Points

Seeking clarification on Type Casting challenge

In the Type Casting challenge, the code ultimately looks as follows:

public static String getTitleFromObject(Object obj) { String result = ""; if ( obj instanceof String){ result = (String) obj; } else if (obj instanceof BlogPost){ BlogPost blog = (BlogPost) obj ; result = blog.getTitle(); } return result; }

Please may someone confirm whether the 'result' variable retains its data type (i.e. type String) throughout?

In task 1 of 2 we assign 'obj' to result and also need to cast 'obj' to String since, up to that point, 'obj' was of type 'Object' (as per the method parameter) and therefore needs to be cast as being of type String since 'result' is of type String (as per the above code).

Then, in task 2, we create a new object (titled 'blog') and cast 'obj' to BlogPost. We then assign 'blog.getTitle()' to 'result'. I believe that this assignment of 'blog.getTitle()' to 'result' only works because the 'getTitle()' method in the BlogPost.java file is also of type String (i.e. the same as 'result').

In other words, for argument's sake, lets assume that the 'getTitle()' method in BlogPost.java was in fact of the int data type. Then I assume that the above code would not work since 'result' is of type String (as declared in the above code) and that would differ to the data type which the 'getTitle()' method returns which would now be of type int.

Please may someone kindly confirm whether my understanding is correct? Sorry for the essay:)

Thanks!

1 Answer

Jake Basten
Jake Basten
16,345 Points

Correct!

result is always a string here. It might be easier to think about the type of the variable, and the type of the value that is assigned to the variable.

For example: To begin with result is assigned an empty String then if obj is a string, result is assigned obj else if obj is a BlogPost, result is assigned the value of obj.getTitle() which is a String

if like you say getTitle returned an int, you would have to cast that to a string to assign the value to result, otherwise you would get an error

Matthew Burkett
Matthew Burkett
3,488 Points

Got it! Thanks a lot Jake!