gpt4 book ai didi

java - 无法创建抽象父类(super class)的非抽象子类?

转载 作者:行者123 更新时间:2023-12-02 06:15:51 26 4
gpt4 key购买 nike

我有一个子类,它声明了我的抽象父类(super class)中的所有方法,但它仍然给我一个错误,指出我的类不是抽象的。我不明白为什么会抛出这个错误。

我收到的具体错误是

PhoneBookEntry.java:1: error: PhoneBookEntry is not abstract and does not override abstract method compareTo(Object) in Comparable

我的问题代码:

public abstract class PhoneNumber implements Comparable
{
protected String firstName, lastName;
protected int number;

public PhoneNumber(String firstName, String lastName, int number)
{
this.firstName = firstName;
this.lastName = lastName;
this.number = number;
}

public abstract String getLastName();
public abstract String getFirstName();
public abstract int getNumber();

public int compareTo(PhoneNumber other)
{
int last = other.lastName.compareTo(lastName);
int first = other.firstName.compareTo(firstName);
int num = other.number - number;
if(last > 0)
return 1;
else if(last < 0)
return -1;
else
if(first > 0)
return 1;
else if(first < 0)
return -1;
else
if(num > 0)
return 1;
else if(num < 0)
return -1;
else
return 0;
}
}

还有我的子类:

public class PhoneBookEntry extends PhoneNumber
{
public PhoneBookEntry(String firstName, String lastName, int number)
{
super(firstName, lastName, number);
}

public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
public int getNumber()
{
return number;
}

public int compareTo(PhoneNumber other)
{
super.compareTo(other);
}

}

最佳答案

这就是问题:

public int compareTo(PhoneNumber other)
{
super.compareTo(other);
}

您已指定您只是实现原始类型 Comparable,该类型的方法签名为:

int compareTo(Object)

最干净的解决方法是将 PhoneNumber 的声明更改为:

public abstract class PhoneNumber implements Comparable<PhoneNumber>

可以实现compareTo(Object),但是您真的希望能够将电话号码与任何其他对象进行比较吗?仅仅声称能够将电话号码与其他电话号码进行比较更有意义(IMO)。

关于java - 无法创建抽象父类(super class)的非抽象子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20083374/

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