2

I'm using an interface in java, that communicates with PureData. In order to do so, my classes have to extend a given class MaxObject. While designing my class, which is a cirular buffer, I discovered that I need to extend java's Iterator class. So I have to extend two classes at the same time.

My guess is that the only solution is to create two different classes and let one of them be a component of the other one. But, is it the only solution? Is it the best one?

Further, whenever I find myself needing inherit from two classes, is it a because of a bad design? Is there a design pattern to solve this class?

Thank you

Leigh
  • 28,765
  • 10
  • 55
  • 103
de3
  • 1,890
  • 5
  • 24
  • 39

3 Answers3

12

Iterator is not a class, it's an interface. As such, you don't extend it, you implement it. You can implement any number of interfaces - the only limitation is that you can only extend one class.

In your case:

class MyClass extends MaxObject implements Iterator<Type>
EboMike
  • 76,846
  • 14
  • 164
  • 167
2

edit: I should have read closer what's being extended. EboMike is right, you don't need to extend the Iterator class.

Sounds like the DDofD: http://javacodeonline.blogspot.com/2009/08/deadly-diamond-of-death.html

Ryan P.
  • 855
  • 2
  • 14
  • 20
  • Great explanation of the DDofD, it makes sense. Anyway, what about c++, how is this problem avoided ? or simply it's not? – de3 Dec 23 '10 at 19:41
  • 3
    Don't do the DDofD in C++. Worst worst case, you can do virtual inheritance, but that's almost always a bad idea. In many cases, you fare better by adding components via "has-a" rather than "is-a". In Java however, implementing several interfaces is perfectly acceptable - that's why Java has the distinction between parent classes and interfaces. – EboMike Dec 23 '10 at 19:45
2

Iterator is an interface. From a theoretical point of view there's nothing against extending MaxObject and implementing Iterator.

Due to a lack of information I cannot say if it's a good idea to do this, but I have a bad feeling.

MRalwasser
  • 15,605
  • 15
  • 101
  • 147