0

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.

3
  • 1
    Homework, by any chance? Commented Feb 26, 2012 at 21:11
  • 1
    How about a good book on design patterns? Commented Feb 26, 2012 at 21:11
  • Here you got something to read janeg.ca/scjp/overload/poly.html Commented Feb 26, 2012 at 21:15

2 Answers 2

4
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

Sign up to request clarification or add additional context in comments.

2 Comments

I assume the collection contains the wheel's brands as well.
I had imagined that each Wheel object would have its own brand attribute.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.