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 Organizing Data Interfaces

Why casting inside a class method?

Why when implementing the compareTo method, the first thing that Craig does is casting to Treet?

We are creating a method inside the Treet class, is it supposed to be a Treet already? If it wasn't, the method applied would be that of Object instead of the one of Treet, right?


Need some help here to fully understand the relationships there!


1 Answer

We are casting the parameter obj to Treet, not this. this is already of type Treet, but obj has the type Object, as declared in the method signature. This is necessary, because we implement the interface Comparable, which expects a method int compareTo(Object). So in order to access any stuff of a Treet instance, we first need to tell Java that this object we pass in is indeed an instance of this class. Nothing prevents us, however, from passing in a Date or an Array. In this case the casting would fail and we would get a runtime exception.

So it's better to implement the generic interface Comparable<T>. The T here is a variable for a type. If we implement this interface, we need to have a method int compareTo(T) --- notice the type of the parameter we pass in. In our case, we want to compare instances of Treet only to other instances of Treet, so we implement Comparable<Treet> and add a method int compareTo(Treet). Now the compiler can check that we only make valid comparisons and we no longer get any exceptions at runtime from invalid type casts.