Reputation: 1
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...
Upvotes: 0
Views: 1094
Reputation: 78945
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);
}
}
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]
Upvotes: 1