gpt4 book ai didi

Java,如何从抽象类继承方法

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:15:27 25 4
gpt4 key购买 nike

我有一个抽象类 Person 和接口(interface)可比,它也用于程序的其他部分。目前我在 Person 中有一个方法 compareTo()。当我尝试编译时,我得到:

The type Student must implement the inherited abstract method 
Comparable<Person>.compareTo(Person, Person)

我到底需要做什么?我不会在任何子类中实现此方法,因为我需要为所有子类(学生、导师、教授等)使用此方法...有更好的方法吗?

接口(interface):

interface Comparable<Element> {
public int compareTo(Element nodeA, Element nodeB);
}

抽象类人:

abstract class Person implements Comparable<Person> {

protected String name;

public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public String toString() {
return name;
}

public int compareTo(Person personB) {
int comp = this.name.compareTo(personB.getName());
return comp;
}
}

和类(class)学生

class Student extends Person implements Comparable<Person> {

private int id;

public Student(String name, int id) {
super(name);
this.id = id;
}

public int getID() {
return id;
}

public void setID(int newID) {
id = newID;
}

public String toString() {
return id + ", " + name;
}
}

最佳答案

更改您的界面:

interface Comparable<Element> 
{
public int compareTo(Element nodeA, Element nodeB);
}

到:

interface Comparable<Element> 
{
public int compareTo(Element nodeA);
}

然后将您的 Person 类定义为:

abstract class Person implements Comparable<? extends Person> { /* ... */ }

并让您的 Student(和其他 Person 子类):

class Student extends Person { /* ... */ }

就是这样。

关于Java,如何从抽象类继承方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8318511/

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