Search code examples
javaclasssubclasssuperclass

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();
i.foo();

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.


Solution

  • 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.