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 trialAnthony Lau
1,898 Pointsdon't know how to pass it
if (obj instanceof String){ return (String)obj; } if( obj instanceof BlogPost){ return (String) obj.getTitle(); }
I think it is right, but it always occur error
import com.example.BlogPost;
public class TypeCastChecker {
/***************
I have provided 2 hints for this challenge.
Change `false` to `true` in one line below, then click the "Check work" button to see the hint.
NOTE: You must set all the hints to false to complete the exercise.
****************/
public static boolean HINT_1_ENABLED = false;
public static boolean HINT_2_ENABLED = false;
public static String getTitleFromObject(Object obj) {
// Fix this return statement to be the correct string.
if (obj instanceof String){
return (String)obj;
}
if(obj instanceof BlogPost){
return (String) obj.getTitle();
}
}
}
2 Answers
Craig Dennis
Treehouse TeacherHmmm...you know that it is a BlogPost
, but then you cast it to a String
. You are super super close.
Let me know if that hint helps. I'll give you another if it doesn't.
Yongshuo Wang
5,500 PointsHi, I follow your code, there are some compile error with it. Please see the code below.
public class TypeCastChecker{
public static void main(String[] args){
BlogPost post = new BlogPost("blog title");
System.out.println("First title is " + getTitleFromObject(post));
System.out.println("Second title is " + getTitleFromObject("Second"));
}
private static String getTitleFromObject(Object obj){
String returnTitle = "";
if (obj instanceof String)
returnTitle = (String) obj;
if (obj instanceof BlogPost)
returnTitle = ((BlogPost)obj).getTitle();
return returnTitle;
}
}