Java Java Data Structures Organizing Data Interfaces

RICARDO SALA
PRO
RICARDO SALA
Pro Student 13,203 Points

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!

THANK YOU!

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.