<分区>
当我遇到一些我无法理解的东西时,我正在练习用 java 编写接口(interface)程序。让我称这个类为 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);