I was practicing to program for interface in java when I came across something I could not understand. Let me call the class 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));
}
}
So the question here is if we declare something as
Object p=new Country(1,2,3);
Object q=new Country(2,3,4);
p.write();
This works. but why not
p.compareTo(q)//as done in the main code
Why is this cast required?
((Comparable)p).compareTo(q);