0

I tried hard to make it. But I've got an error message "Student is not abstract and does not override abstract method compareTo(Object) in Comparable class Student extends Person {"

abstract class Person implements Comparable {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

class Student extends Person {
    private int id;

    public Student(String name, int id) {
        super(name);

        this.id = id;
    }

    public String toString() {
        return Integer.toString(id);
    }

    public int getId() {
        return this.id;
    }

    @Override
    public int compareTo(Student s) {
        if (this.id < s.getId()) {
            return -1;
        }else if (this.id > s.getId()) {
            return 1;
        }
        return 0;
    }
} 
@Override
    public int compareTo(Student s) {
        if (this.id < s.getId()) {
            return -1;
        }else if (this.id > s.getId()) {
            return 1;
        }
        return 0;
    }

this is where I think having a problem...

  • 1
    Your `Comparable` is a *raw* generic. Don't use raw generics. See: [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/q/2770321/5221149) – Andreas Mar 31 '20 at 01:15
  • Why do you put `implements Comparable` on `Person`, when you can't compare two persons of different subclasses anyway? E.g. comparing a `Student` and a `Teacher` would throw `ClassCastException` --- Make `Student` do the `implements Comparable`, not `Person`. – Andreas Mar 31 '20 at 01:17

1 Answers1

1

As already explained by @Andreas, make Student implements Comparable, not Person.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

abstract class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

class Student extends Person implements Comparable<Student> {
    private int id;

    public Student(String name, int id) {
        super(name);

        this.id = id;
    }

    public String toString() {
        return Integer.toString(id);
    }

    public int getId() {
        return this.id;
    }

    @Override
    public int compareTo(Student o) {
        return Integer.compare(this.id, o.id);
    }
}

Demo

public class Main {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<Student>();
        list.add(new Student("Abc", 321));
        list.add(new Student("Xyz", 12));
        list.add(new Student("Mnp", 123));
        Collections.sort(list);
        System.out.println(list);
    }
}

Output:

[12, 123, 321]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110