The method signature accepts an object of type Object , therefore, in order to refer to the priority variable inside the passed object, it must cast the Task object, since the variable exists only in the Task class.
Personally, I think this was bad practice, since you donβt know which object is being passed (any class of subclasses of the Object class can be passed), so the validation instance will not go the way you want to throw a ClassCastException runtime error.
Alternatively, you can use generics to indicate which object you want to compare to. Therefore, instead ...
public class Task implements Comparable { private int priority = 1; @Override public int compareTo(Object o) { if (o instanceof Task) { Task t = (Task) o; return this.priority < t.priority; } return -1; } }
... you could do it ...
public class Task implements Comparable<Task> { private int priority = 1; @Override public int compareTo(Task t) { return this.priority < t.priority; } }
source share