If you are sure at the point where you are using i
, that i
is definitely of type MainIterator
, it is alright to cast it. Also, if you are sure that you need a concrete MainIterator instance at this point, then you can simply type it as MainIterator i = new MainIterator()
. For both cases it means that your design is tightly coupled to a particular implementation, which defeats the purpose of using an interface. So at this point I'd take a look at the design to make sure that happens where you are sure that all you need is an instance of MainIterator
and no other instance.
If you must use Iterator
but i
can be any implementation of Iterator
, you have a design problem because you are tightly coupled to a particular implementation (because you want to use the void foo
method), but your code also wants to work with all implementations. This is a contradiction that you have to resolve, and it is hard to say how you can rectify it without looking at your overall design.