0

I've been having problems about this:

public class Student implements Comparable {
    private int id;
    private String name;



    public int compareTo(Student other) {
       return 1; // This is just an example value

    }
}

This program doesn't compile, as it says that it doesn't override the method "compareTo()" . Now why is that?

But if I use the following class header

public class Student implements Comparable<Student>{...}

it works fine. I need some explanation about this. By the way a lot of internet examples of the "Comparable" interface use the first class header, I mean without the Comparable.

1ac0
  • 2,875
  • 3
  • 33
  • 47
FraK
  • 919
  • 1
  • 13
  • 21

1 Answers1

0

Look at the source code of Comparable. With implements Comparable the method within student would be

public int compareTo(Object other) { ...

Using generics Comparable the method is like you wrote it.

By the way the compiler should have given you a helpful explanation.

wumpz
  • 8,257
  • 3
  • 30
  • 25
  • Yes it does compile using an Object as a parameter. But I've seen lots of examples where it doesn't use the method with "Object". Most of them use the same class a a parameter. Are all of these examples wrong ? just have a quick look over the web and you will see what I'm talking about. This really confuses me. But at the end, what is the "right" way to do it. Or the most appropriate ?. – FraK Feb 17 '14 at 17:10
  • I dived shortly into the net and could not find the wrong examples. – wumpz Feb 18 '14 at 06:16