aspose file tools*
The moose likes Java in General and the fly likes a question about Comparable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "a question about Comparable " Watch "a question about Comparable " New topic
Author

a question about Comparable

sergios agapiou
Greenhorn

Joined: Jul 10, 2005
Posts: 2
Can u please tell me why when i write code to implement compareTo(Object o) of Comparable i have to write object o as a parameter?
I am trying to give sub-types of Object there so i don't have to cast later in the method's body.
When i do that i can't compile.

I did the same thing with clone(Object o) of Cloneable and there was no problem.
Thanks for ur time.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi,

To implement an interface, you have to provide definitions for all of its methods. If you change the argument types of a method, you get a new method -- this is called overloading. It's possible for a class to have multiple overloaded versions of a single method -- like the many println() methods in the java.io.PrintWriter class. In any case, when you're implementing an interface, your implementation has to match the method declaration exactly. Because the compareTo() method in Comparable is declared to take an Object, your implementation has to, as well.

Now, clone() is a different case. First of all, it's not defined in an interface; it's a protected method in Object. The Cloneable interface is empty. When you implement clone(), what you have to do is override the version in Object, again, matching the signature exactly; but if you change it, you won't get an error -- you just won't actually be making your object Cloneable. Note, also, that clone() takes no arguments -- if you were implementing clone(Object) or clone(Foo), this has nothing whatsoever to do with the Cloneable interface -- you're just overloading the method; this is legal, but not germane to this discussion.

Finally, note that the new generics feature in JDK 1.5 lets you declare something to be Comparable<Foo>, such that you can then write compareTo() to take an argument of the correct type. This works only in JDK 1.5, though.


[Jess in Action][AskingGoodQuestions]
sergios agapiou
Greenhorn

Joined: Jul 10, 2005
Posts: 2
Thank u very much for your answer!
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
You are referring to 'parametric polymorphism', which is not supported by Java.


Tony Morris
Java Q&A (FAQ, Trivia)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: a question about Comparable