当前位置: 首页 > 知识库问答 >
问题:

人类不是抽象的,不重写抽象方法compareTo(人类)。解决方案?

司国源
2023-03-14
public class Human implements Comparable<Human> {
    private int age;
    private String name;

    public Human(String givenName, int age) {
        this.name = givenName;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String introduce() {
        return "Hey! I'm " + name + " and I'm " + age + " years old.";
    }

    public int CompareTo(Human h1, Human h2) {
            int hum1 = h1.getAge();
            int hum2 = h2.getAge();
            System.out.println(hum1 - hum2);
    }
}

这里怎么了?请帮忙。

共有1个答案

裴俊智
2023-03-14

您要更改:

public int CompareTo(Human h1, Human h2)

致:

public int compareTo(Human h_other)

两件事:首先,“C”是小写的。其次,compareto方法将这个与另一个human进行比较,因此它等效于(使用旧代码):

public int compareTo(Human h_other) {
    return CompareTo(this, other);
}
 类似资料: