java - 为什么调用接口(interface)继承的方法需要强制转换?

标签 java inheritance casting

当我遇到一些我无法理解的东西时,我正在练习用 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);

最佳答案

这里:

Object p=new Country(1,2,3);

编译器可以知道p 是Country 类型。但它并不知道。

它只看到您将 p 声明为 Object 类型。并且 Object 类没有 print() 方法或 compareTo() 方法。

多态性(在对象的实际类型上查找方法)发生在运行时,但确定某个对象是否具有特定方法发生在编译时。在这种情况下,编译器决定:p 是一个 Object,因此它缺少您要调用的方法!

关于java - 为什么调用接口(interface)继承的方法需要强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56732259/

相关文章:

java - 在Java中,我如何构造一个for循环来找到输入的十个值的最大值和最小值。我目前没有收到该程序的输出

java - Android 将两个按钮对齐在同一行

java - Elasticsearch 5.1 批量操作

c# - 在基类中使用的继承类中创建的对象

c++ - 抽象基类(成员变量)的 shared_ptr 是一个未声明的标识符

java - Spring boot @Qualifier 不适用于数据源

c++ - C++中的多级构造函数

c++ - 带接口(interface)的动态转换

javascript - 将变量名作为字符串循环并销毁它们

casting - 在IDL中将2个字节转换为一个16位整数