Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么调用从接口继承的方法需要强制转换?_Java_Inheritance_Casting - Fatal编程技术网

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) { /*

我在练习用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)
    {
    /*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是的,问题是重复的,回答了我的问题。哦,要问一个不重复的问题太难了。