Java 为什么调用从接口继承的方法需要强制转换?
我在练习用java编写接口程序时,遇到了一些我不懂的东西。让我给这个班级打电话Java 为什么调用从接口继承的方法需要强制转换?,java,inheritance,casting,Java,Inheritance,Casting,我在练习用java编写接口程序时,遇到了一些我不懂的东西。让我给这个班级打电话 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) { /*
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));
}
}
这很有效。
但为什么不呢
p.compareTo(q)//as done in the main code
为什么需要这个演员
((Comparable)p).compareTo(q);
因为您将值存储在
Object
类型的引用中,所以编译器无法知道它实际上是国家
,并且它实现了可比
。因为您将值存储在Object
类型的引用中,所以,编译器无法知道它实际上是一个国家,并且它实现了可比较的。这里:
Object p=new Country(1,2,3);
编译器可能知道p
属于Country类型。但它不知道
它只会看到您将p
声明为Object
类型。类对象没有print()
方法或compareTo()
方法
多态性(查找对象实际类型的方法)发生在运行时,但决定某个对象是否有特定方法发生在编译时。在这种情况下,编译器决定:p
是一个对象,因此它缺少要调用的方法 这里:
Object p=new Country(1,2,3);
编译器可能知道p
属于Country类型。但它不知道
它只会看到您将p
声明为Object
类型。类对象没有print()
方法或compareTo()
方法
多态性(查找对象实际类型的方法)发生在运行时,但决定某个对象是否有特定方法发生在编译时。在这种情况下,编译器决定:p
是一个对象,因此它缺少要调用的方法 注意:您应该使用类国家/地区实现可比较的-避免。p.write()代码>也不起作用,至少对我来说是这样。我不知道你做了什么使它工作。另外,我强烈怀疑你的compareTo
实现是否符合Comparable
interface@Slaw我确实知道通用接口,但我的问题是关于这个接口的。@GhostCat是的,问题是重复的,回答了我的问题。哦,问一个不重复的问题太难了。注意:你应该使用类-避免。p.write()代码>也不起作用,至少对我来说是这样。我不知道你做了什么使它工作。另外,我强烈怀疑你的compareTo
实现是否符合Comparable
interface@Slaw我确实知道通用接口,但我的问题是关于这个接口的。@GhostCat是的,问题是重复的,回答了我的问题。哦,要问一个不重复的问题太难了。