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

angel juarez
angel juarez
15,886 Points

I'm having problems with the casting challenge. I can't cast the object as a blogpost.

I'm using the method that returns a String, but I can't get to return the title, because I can't cast the object as blogpost

com/example/BlogPost.java
package com.example;

import java.util.Date;

public class BlogPost {
    private String mAuthor;
    private String mTitle;
    private String mBody;
    private String mCategory;
    private Date mCreationDate;

    public BlogPost(String author, String title, String body, String category, Date creationDate) {
      mAuthor = author;
      mTitle = title;
      mBody = body;
      mCategory = category;
      mCreationDate = creationDate;
    }

    public String getAuthor() {
      return mAuthor;
    }

    public String getTitle() {
      return mTitle;
    }

    public String getBody() {
      return mBody;
    }

    public String getCategory() {
      return mCategory;
    }

    public Date getCreationDate() {
      return mCreationDate;
    }
}
TypeCastChecker.java
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 result variable to be the correct string.

    if(obj instanceof BlogPost){
        BlogPost result = (BlogPost) obj;
    }
    return result.getTitle();
  }
}

5 Answers

Jonathan Hector
Jonathan Hector
5,225 Points
  public static String getTitleFromObject(Object obj) {
    // Fix this result variable to be the correct string.
   BlogPost result = new BlogPost(); //This way of casting is a better 'good practice' to avoid errors
    if(obj instanceof BlogPost){
       result = (BlogPost) obj;
    }
    return result.getTitle();
  }
Karim Zibari
Karim Zibari
7,358 Points

It's a scope issue. You should declare the object 'result' outside the if-statement.

I'm going to break everything down in minute detail and tie the previous two answers together so you might be able to fully understand what's going on here.

The first thing is variable scope. In this context, it's helpful to think of scope as how long a variable is alive for. As long as it is alive, you can reference it with its name (its variable name). Now, variables live and die within curly braces {}. If you declare a variable within a set of curly braces, it dies as soon as you exit the curly braces. Once it dies, you can't reference it anymore with its name; it doesn't exist anymore. Here's what you wrote:

if(obj instanceof BlogPost){
        BlogPost result = (BlogPost) obj;
    }
return result.getTitle();

Notice how your if-statement has a set of curly braces, and you declare the variable result within those curly braces. That is why when you try to return result.getTitle(), you get an error - it already died because you have exited the curly braces {}. Jonathan Hector has the right idea to fix this: declare the variable before the if-statement.

(Note that within one set of curly braces {} you can make another set of curly braces {}, and anything declared within the outer set is still alive (still "in scope") in the inner set. This is exactly what the correct answer has going on. getTitleFromObject() has a set of curly braces {}, and, within that, you have an if-statement with its own set of curly braces {}. The correct answer has the variable result declared within the getTitleFromObject() curly braces {} and then you re-assign its value to (BlogPost) obj within the if-statement's curly braces {}. This is completely legal. )

Sorry if this was long-winded, but I hope that was an exhaustive explanation so you can spot problems like this in the future!

Lior Avital
Lior Avital
2,416 Points

All the variables that you declare inside the if statement are local to the if statement. When the execution is past the closing brace "}" these variables are discarded and can't be used anywhere else.

When you declare the variable before the if statement, you can use it after the if statement closing brace.

In order to make this class viable first of all:

When you are creating a class for inherentence

Create an abstract class since your assigning values but simply declaring class members and methodes.

For Example

package com.example;

import java.util.Date;

public abstract class Blogpost { private String mAuthor; private String mTitle; private String mBody; private String mCategory; private Date mCreationDate;

public BlogPost(String author, String title, String body, String category, Date creationDate) { mAuthor = author; mTitle = title; mBody = body; mCategory = category; mCreationDate = creationDate; }

public String getAuthor() { return author; }

public void setAuthor(String author) { this.author = author; }

public String setTitle(String Title) { this.Title = Title; } public void getTitle() { return Title; } }

Just a few examples of when u use the get method u should also use the setmethod for things to work.