views:

132

answers:

1

Hi,

If I have a superclass, say Animal,

and two subclasses: Zebra and Giraffe,

If I decide to define a Vector of Animals:

Vector <Animal> animals = new Vector();

and I want to say: You can add Giraffes, but you must own at least one Zebra first.

What is the best way to do this without using RTTI? (instanceof)

+4  A: 

Define your own class:

class Animals extends Vector<Animal>
{
   public Animals(Zebra z) { add(z); }
}

Two additional points:

  • It is recommended to prefer the use of ArrayList over Vector.
  • You may want to override the remove() method to make sure a Zebra always stays in the collection.

Personally, I would go for a design that does not use inheritance at all. So instead of subclassing vector (or ArrayList) my class will delegate to them:

class Animals extends 
{
   private final Vector<Animal> inner = new Vector<Animal>();

   public Animals(Zebra z) { add(z); }

   // Delegate to whatever methods of Vector that Animals need to support, e.g.,
   void add(Animal a) { inner.add(a); }

   ...
}
Itay
+1 for recommending delegation in place of inheritance as well as for pointing out that ArrayList is preferred over Vector.
Michael Aaron Safyan