![](/img/trans.png)
[英]ClickableSpan - Class is not abstract and does not override abstract method
[英]Class is not abstract and does not override abstract method problem
我努力做到了。 但是我收到一條錯誤消息“Student 不是抽象的,並且不會覆蓋 Comparable 類 Student extends Person { 中的抽象方法 compareTo(Object)”
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;
}
這就是我認為有問題的地方......
正如@Andreas 已經解釋過的,讓Student implements Comparable
,而不是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);
}
}
輸出:
[12, 123, 321]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.