Ken Y-N
Ken Y-N

Reputation: 15009

Subclass as a collection of classes

In Java we could have (assume extra constructor methods, etc):

class Car
{
    public void Vrooom() { System.out.print("Vrooom!"); }
}

class Prius extends Car
{
    public void Vrooom() { System.out.print("..."); }
}

class Cars extends Car
{
    private ArrayList<Car> mCars;
    public void Vrooom() { for(Car car: mCars) car.Vrooom(); }
}

I came across code doing something like this, but Cars doesn't feel right to me, as it has to override every single Car method to add the for loop. Is this an anti-pattern, and if so, why should I not do this?

Upvotes: 2

Views: 54

Answers (2)

Prasad Kharkar
Prasad Kharkar

Reputation: 13556

You are inheriting a car to represent a list of cars? You don't need to do this. If you simply want a list of cars, then you can create

List<Car> list = new ArrayList<Car>();

Inheritance means the subclass should pass IS-A test for superclass and in your case, the list of cars is not exactly a car.

Upvotes: 2

user764357
user764357

Reputation:

You're right, something about that feels wrong. In my mind a collection of objects shouldn't extend that object as well.

It may be the case that you have a Dealership that holds some cars, but I would think you would do that like (and I don't java so I might screw up the syntax a little):

class Dealership extends Businesses
{
    private private ArrayList<Car> sellableCars;

    public void itsAHugeSalesSpectacular() {
        for(Car car: sellableCars) car.Vrooom(); 
    }
}

But in my experience there is no reason that you'd define the cars of the dealership as an object in its own right.

Upvotes: 2

Related Questions