Reputation: 57
As an example, I have a Car
class. When I create a car object I would like to pass the number of wheels I would like that car to have and the constructor would create Wheel
objects from 1-x
number of wheel objects I passed to the Car
's constructor.
Any help you can provide would be greatly appreciated!
Parent is Car
Child is Wheel
Upvotes: 1
Views: 1058
Reputation: 4899
The relationship of a car with its wheels is a has a relationship. A car has wheels. This being modelled through inheritance is semantically incorrect as inheritance is an is a relationship. A car is not a wheel. Has a relationship must be modelled through composition. A car contains multiple wheels. Use a collection like an array that holds the wheels for each car:
class Wheel {
}
class Car {
// Use an array to hold the wheel objects
private Wheel[] wheels;
private String name;
public Car(String name, int wheelCount) {
this.name = name;
wheels = new Wheel[wheelCount];
for(int i = 0; i < wheelCount; i++) {
wheels[i] = new Wheel();
}
}
public void changeWheelAt(int index, Wheel wheel) {
wheels[index] = wheel;
}
public Wheel getWheelAt(int index) {
return wheels[index];
}
public Wheel[] getWheels() {
return wheels;
}
public String getCarName() {
return name;
}
public int getNumberOfWheels() {
return wheels.length;
}
}
Upvotes: 2
Reputation: 94
I hope you do not actually mean that the Car class is the parent of Wheel. That would be an IS-A relationship. We do know that a wheel IS-NOT-A car.
What we might want to use here is the many-to-one composition (HAS-A) relationship between Wheel and Car. Most cars HAVE wheels!
So something like:-
public class Car {
...
Set<Wheel> wheels;
}
Then you could have a constructor wherein you could pass the number of wheels and the set would be initialized.
public class Car {
Car(int numOfWheels) {
wheels = new HashSet<>();
for(int i=0; i<numOfWheels; i++) {
wheels.add(new Wheel());
... // Other Wheel properties
}
}
...
Set<Wheel> wheels;
}
Upvotes: 1