Reputation: 319
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)
Upvotes: 0
Views: 805
Reputation: 30733
Define your own class:
class Animals extends Vector<Animal>
{
public Animals(Zebra z) { add(z); }
}
Two additional points:
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); }
...
}
Upvotes: 6