【发布时间】:2019-11-06 00:08:49
【问题描述】:
当我遇到一些我无法理解的东西时,我正在练习用 Java 编写接口。让我将班级称为 Country
class Country implements Comparable
{
int a;
int b;
int c;
public Country(int _a,int _b,int _c)
{
a=_a;
b=_b;
c=_c;
}
public int compareTo(Object obj)
{
/*compares a, b and c and returns number of variables greater for this object.I am not include instanceof check*/
int count=0;
Country other=(Country)other;
if(a>other.a)
count++;
else
if(a<other.a)
count--;
if(b>other.b)
count++;
else
if(b<other.b)
count--;
if(c>other.c)
count++;
else
if(c<other.c)
count--;
return count;
}
public void write()
{
System.out.println(" hello");
}
public static void main(String args[])
{
Object p=new Country(1,2,3);
Object q=new Country(2,3,4);
System.out.println(p.compareTo(q));
}
}
所以这里的问题是我们是否将某些东西声明为
Object p=new Country(1,2,3);
Object q=new Country(2,3,4);
p.write();
这行得通。 但为什么不呢
p.compareTo(q)//as done in the main code
为什么需要这个演员表?
((Comparable)p).compareTo(q);
【问题讨论】:
-
注意:您应该使用
class Country implements Comparable<Country>——避免使用raw types。 -
p.write();not 也不起作用,至少对我而言。不知道你做了什么让它工作。 -
另外,我强烈怀疑您对
compareTo的实现是否符合Comparable接口的formal requirements -
@Slaw 我确实知道通用接口,但我的问题特别是关于这个。
-
@GhostCat 是的,其中重复的问题回答了我的问题。哦,问一个不重复的问题真是太难了。
标签: java inheritance casting