user2359626
user2359626

Reputation: 63

When a class "has a" relationship with other class objects

Let's say we have a Car, Wheel, and Brakes classes. A Car "has" four wheels so when an instance of Car is created, I want 4 instances of Wheels created at the same time. Likewise if I were creating a Motorcycle, I would want two instances of Wheels created. My question is how do I best create the Wheel instances and name them when creating a Car class?

Now suppose you want to assign the brakes to specific wheels- i.e.: FrontBrakes are attached to frontLeft, frontRight Wheels. Should I try to make a property in the Wheel class called AttachedTo? How do I assign ownership so to speak of the brakes to specific wheels?

public class Car
{
    public Car()
    {
        Wheel frontLeft = new Wheel();
        Wheel frontRight = new Wheel();
        Wheel backLeft = new Wheel();
        Wheel backRight = new Wheel();
        Brake frontBrakes = new Brake();
        Brake backBrakes = new Brake();
    }
}

public class Wheel
{
    public int Size;
    public string Brand;
    public Brake AttachedTo { get; set; }
}

public class Brake
{
    public string Type;
}

Upvotes: 0

Views: 2140

Answers (3)

tinstaafl
tinstaafl

Reputation: 6948

Since the wheel positions and the brake types are constants, enums would probably be appropriate. Then wheel position and brake type would be properties in the wheel class. Make the braketype read only and set it in the constructor according to the wheel position.

Upvotes: 0

KennyZ
KennyZ

Reputation: 907

I would suggest that the car does not have brakes directly, the car has wheels and the wheels have brakes.

I would also suggest that you subclass Wheel with FrontWheel and BackWheel. If you dont, then at the very least, wheel should have a FrontOrBack property, and this needs to be specified in the constructor.

Upvotes: 0

jeffo
jeffo

Reputation: 410

Definitely do not make an attached to property. I would just make the wheels a property on the appropriate class, but a property called attached is an awkward approach.

This looks like a good use of the Builder pattern.
http://www.dofactory.com/Patterns/PatternBuilder.aspx

In general use SOLID and prefer composition over inheritance. http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)

Upvotes: 3

Related Questions