【问题标题】:Why is cast necessary for calling methods inherited from interfaces? [duplicate]为什么调用从接口继承的方法需要强制转换? [复制]
【发布时间】:2019-11-06 00:08:49
【问题描述】:

当我遇到一些我无法理解的东西时,我正在练习用 Java 编写接口。让我将班级称为 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);

【问题讨论】:

  • 注意:您应该使用class Country implements Comparable&lt;Country&gt;——避免使用raw types
  • p.write(); not 也不起作用,至少对我而言。不知道你做了什么让它工作。
  • 另外,我强烈怀疑您对compareTo 的实现是否符合Comparable 接口的formal requirements
  • @Slaw 我确实知道通用接口,但我的问题特别是关于这个。
  • @GhostCat 是的,其中重复的问题回答了我的问题。哦,问一个不重复的问题真是太难了。

标签: java inheritance casting


【解决方案1】:

这里:

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

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

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

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

【讨论】:

    【解决方案2】:

    因为您将值存储在Object 类型的引用中,所以编译器无法知道它实际上是Country 并且它根本实现Comparable

    【讨论】:

      猜你喜欢
      • 2015-01-29
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      • 2010-10-29
      • 2012-04-12
      相关资源
      最近更新 更多