gpt4 book ai didi

java - 类不是抽象的,不重写抽象方法问题

转载 作者:行者123 更新时间:2023-12-02 08:48:20 31 4
gpt4 key购买 nike

我很努力地做到了。但我收到一条错误消息“Student 不是抽象的,也不会重写 Comparable 中的抽象方法compareTo(Object)类 Student 扩展 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;
}

这是我认为有问题的地方......

最佳答案

正如 @Andreas 已经解释的那样,让 Student 实现 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]

关于java - 类不是抽象的,不重写抽象方法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60941754/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com