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

Typecasting the treet

In the code, there is a point where he passes in an Object, then typecasts it as a Treet. Why doesn't he just pass in a Treet to begin with, and skip that point completely? Is this necessary? Or would it work just fine to just start out with "int compareTo(Treet other)"?

Sorry, this should be in reference to this video:

https://teamtreehouse.com/library/java-data-structures/organizing-data/interfaces

Not sure how I managed to post outside of it...

1 Answer

I assume you are asking about the following code:

@override
public int compareTo(Object obj) {
   Treet other = (Treet) obj;
...

One of the "rules" for overriding methods like equals() and compareTo() is you should write them so they accept any object as a parameter. So the first thing you need to do is see if the incoming object is really what you are expecting, and then, if it is, to cast it.
It's not enough if a Treet is passed in. Here the instructor leaves out the usual line that checks to see if Object obj really is a Treet. It it isn't the cast would fail. So what many would do is is the following, just to be safe, even if they are sure nothing but Treets will be passed in:

@override
public int compareTo(Object o) {
   if (obj instanceof Treet) {
      Treet other = (Treet) obj;
      ...
   }
}