sab
sab

Reputation: 10007

Variable arguments in java constructor

Ho can I implement a Car class in the sample below. I can pass a collection with wheel to brand mapping but is there a better way of doing it?

A Car has an engine and some number of wheels. Not all cars are built to hold four wheels, some have only three while others have more. But whatever they are built for, that is the max number they can hold.When a car is built (i.e. constructed), an engine is created for it and so are the wheels that it will use.

Upvotes: 0

Views: 4851

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533880

There are many ways to do this, but there is not enough information to say which might be better.

I suggest you do what you believe is the simplest and clearest, and if passing a collection works for you, do that.

Upvotes: 0

Hunter McMillen
Hunter McMillen

Reputation: 61550

public class Car
{
    private Engine      e;
    private int         numWheels;
    private List<Wheel> wheels;

    public Car(Engine e, int numWheels, ...)
    {
       this.e         = e;
       this.numWheels = numWheels;
       this.wheels    = new ArrayList<>();

       for(int i = 0; i < this.numWheels; i++)
       {
           this.wheels.add(new Wheel(...));
       }
    }
}

Just add an integer that holds the number of wheels THIS Car object can have. Then loop through in the constructor and add those wheels

Upvotes: 4

Related Questions