Java Java Data Structures Getting There Type Casting

Phoenix S.
Phoenix S.
2,456 Points

I've watched and re-watched the video a few times... can someone explain to me why this worked for step 1?

The more someone could break it down for me the better it's a bit difficult to wrap my head around

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.
    String result =  (String) obj;
    return result;
  }
}
Emmanuel C
Emmanuel C
7,639 Points

I copied and pasted your code into step one and it didn't pass for me. It expected me to check if the obj being passed is a String using instanceof.

Phoenix S.
Phoenix S.
2,456 Points

When I re-started the exercise to try and make it happen again it didn't work for me either lol. Thanks to the help of one of our senior devs I was able to come up with this:

  public static String getTitleFromObject(Object obj) {
    // Fix this result variable to be the correct string.
    String result = "";
    if (obj instanceof String) {
      result = (String) obj;
    }
    return result;
  }