Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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;
      ...
   }
}