use*_*825 2 java oop inheritance compiler-errors abstract
我有一个子类声明我的抽象超类中的所有方法,但它仍然给我一个错误,说明我的类不是抽象的.我无法弄清楚为什么会抛出这个错误.
我得到的具体错误是
PhoneBookEntry.java:1:错误:PhoneBookEntry不是抽象的,并且不会覆盖Comparable中的抽象方法compareTo(Object)
我的代码有问题:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
而我的子类:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 10
这就是问题:
public int compareTo(PhoneNumber other)
{
super.compareTo(other);
}
Run Code Online (Sandbox Code Playgroud)
您已经指定您只是实现原始类型Comparable,它具有签名为的方法:
int compareTo(Object)
Run Code Online (Sandbox Code Playgroud)
对此最干净的解决方法是将声明更改PhoneNumber为:
public abstract class PhoneNumber implements Comparable<PhoneNumber>
Run Code Online (Sandbox Code Playgroud)
你可以实现compareTo(Object),但你真的希望能够将电话号码与任何其他对象进行比较吗?声称能够将电话号码与其他电话号码进行比较更有意义(IMO).
| 归档时间: |
|
| 查看次数: |
830 次 |
| 最近记录: |