I have a class MyDoublyIterator<E>
that implements the Iterator<E>
interface. Also, it has a couple other methods not part of the interface (for example public void boolean hasPrev()
). When I try to call that method in my main class my IDE can't resolve that method.
Here's the code I'm using to call it
Iterator<String> di = new MyDoublyIterator<String>();
di.hasPrev();
So I guess my question why can't it find that method. Do I have to build an abstract class that im开发者_开发百科plements the interface and extend it?
The Problem is that the di-variable is of the type Iterator. So it could contain any implementation of this interface. And therefore the IDE cannot be sure that it contains an instance of MyDoublyIterator. So to make it work like you requested, you have to change the type of the variable to MyDoublyIterator.
It is better to first extend the original interface Iterator<E>
with your own interface eg: DoubleIterator<E>
with additional methods like hasPrev()
and then implement the newly created interface DoubleIterator<E>
in your class MyDoublyIterator<E>
.
Otherwise you can instantiate your class like this:
MyDoublyIterator<String> di = new MyDoublyIterator<String>();
di.hasPrev();
Then compiler won't complain since you are creating a type of MyDoublyIterator<E>
.
When compiler sees di.hasPrev();
It only knows that di
is Iterator<String>
and has no clue that it's your own type. So it is not aware of your custom methods.
Iterator<String> di = new MyDoublyIterator<String>();
di.hasPrev();
It won't help you. Compiler needs a way to know that your own interface has that method, and not the built-in interface Iterator interface i.e Iterator<String>
. Here, you are creating a reference for the built-in Iterator interface i.e Iterator<String>
.
Hence, if you have your own interface named MyDoublyIterator<E>
and this interface has the method named hasPrev();
you need to do this :
MyDoublyInterface<String> di = new MyDoublyIterator<String>();
di.hasPrev();
and then it will resolve the method call, since it knows that you have created a reference of your own MyDoubleInterface<T>
and it should solve the problem now. :-)
Other answers are correct, but here's another spin - create an interface that extends
Iterator:
interface DoublyIterator<E> extends Iterator<E> {
boolean hasPrev();
}
class MyDoublyIterator<E> implements DoublyIterator<E> {
// ... implement methods
}
DoublyIterator<String> di = new MyDoublyIterator<String>();
di.hasPrev();
精彩评论