Subclass with additional method in 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...

and in my main class I call:

Iterator i = new MainIterator();;

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();

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

Iterator i = new MainIterator();

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.

You can declare your variable as MainIterator:

MainIterator i = new MainIterator();;

Or you can cast:

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

There are no other ways to do it.

Need Your Help

Segoe UI Symbol emoji character not displaying in colour on Windows Phone 8.1

c# windows-phone-8 colors character winrt-xaml

On Windows Phone 8, the following xaml displays an emoji character in colour:

How to improve website performance on iPad/iPhone?

jquery android iphone performance ipad

On an average computer animations work very smoothly. On iPad however jQuery animations like fade in (opacity from 0 to 1 over 0.5 sec) of 1920x1200px image seem to lag a bit.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.