Java Java Data Structures Organizing Data Interfaces

when the Craig type casted the object into a Treet. what will the obj contain, is it the treet or the secondTreet ?.

Hello Good people, when Craig type caste the object into a Treet. what will the obj contain, is it the treet or the secondTreet ?. And my other question is can you typecast Object as a Treet (upward Casting) without first type casting Treet as an Object (down casting).since in java-repl if you create an Object and try to type caste explicitly as a Treet it will through an error(java.lang.ClassCastException: java.lang.Object cannot be cast to com.teamtreehouse.Treet).

thanks for your time.

Hi. Upcasting will work without problems. As a matter of fact that is what is happening in the method signature:

@Override
public int compareTo(Object obj){ ...

Whatever is passed in to the compareTo method (likely a Treet) will be an Object. Everything instance in java is polymorphic as every instance is the datatype of the reference as well as the parent Object class. So it is safe to just store the argument as an Object. But now that it is an Object, it doesn't have all of its children methods and properties (with the children methods and properties being the methods and properties belonging to the actual type that was passed in to the method in question. So, to ensure that you can access the properties and methods of Treet, you must cast that Object as a Treet:

(Treet) obj

Since this method is in the Treet class itself, the object that is passed in could be anything. Take the following from Example.java:

Treet treet = new Treet(
  "craigdennis",
  "Want to be famous?  Simply tweet about Java and use the hashtag #treet. " +
  "I'll use your tweet in a new @treehouse course about data structures.",
  new Date(1421849732000L)
);


Treet secondTreet = new Treet(
  "journeytocode",
  "@treehouse makes learning Java sooo fun! #treet",
  new Date(1421878767000L)
);

Since both treet and secondTreet are instances of the Treet class, theyboth will have the compareTo method. so you could use either one:

treet.compareTo(secondTreet)

or secondTreet.compareTo(treet)

I hope that makes sense.

1 Answer

Tonnie Fanadez
Tonnie Fanadez
UX Design Techdegree Graduate 21,841 Points

Just paraphrasing the above comment by sjules.

Whatever is passed in to the compareTo method (likely a Treet) will be an Object. Everything in java is an instance of the the parent Object class, therefore it is safe to just store the argument as an Object. However the parent Object Class doesn't have all of its children methods and properties (with the children methods and properties being the class Treet methods and attributes) So, to ensure that you can access the properties and methods of Treet, you must cast the Object as a Treet