使用Java中的其他方法的子类 [英] Subclass with additional method in Java

查看:107
本文介绍了使用Java中的其他方法的子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有一个子类的问题。我有以下类:

I have a problem with a subclass in Java. I have the following class:

MainIterator implements Iterator{
   //... Methods from the interface Iterator

   public void foo(){
      //Do something...
   }
}

并在我的主类中调用:

Iterator i = new MainIterator();
i.foo();

这不起作用,因为Iterator没有实现函数 foo >。如何可以得到这个工作没有类型的 i i 必须来自类型Iterator。

which does not work, because Iterator does not implement the function foo(). How is it possible to get this working without a typecast of i? i has to be from type Iterator.

推荐答案

MainIterator i = new MainIterator();

Java编译器只允许调用属于声明的类型的方法变量。如果你使用

The Java compiler only allows calling methods that belong to the declared type of the variable. If you use

Iterator i = new MainIterator();

你告诉编译器:我创建一个类型为MainIterator的Iterator实例,但是你不需要在其余代码中知道这一点。只需将此对象视为Iterator的实例。而且Iterator没有任何foo()方法。

you're telling the compiler: I create an instance of Iterator which is of type MainIterator, but you don't need to know about that in the rest of the code. Just consider this object as an instance of Iterator. And Iterator doesn't have any foo() method.

这篇关于使用Java中的其他方法的子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆