The Scenario
I'm making a program in Java that involves cars.
NOTE: I've simplified this scenario (to the best of my ability) to make it both more general and easier to understand. I'm not actually working with cars.
I've created a Cars class, which is a collection of Car objects.
The Car object has a speed (double) and a year (int). The constructor takes the year as a parameter, for example:
public class Car {
private int year;
private double speed;
public Car(int year) {
this.year = year;
}
}
Here's the tricky part... A car must have a kind (let's say Corvette or Clunker). A Corvette will have a speed of 0.9 and a Clunker will have a speed of 0.1. A Car can never be instantiated without specifying what kind of car it should be. So now, to create a car, we have:
Car car = new Car(1998, Corvette);
The Corvette we've just created will be a Car object with a speed of 0.9.
The Problem
My actual situation involves many more kinds of cars, and each car has several specific attributes besides speed (maybe there are also fields for color, numDoors and fuelTankSize). With so many kinds of cars (each with their own specific attributes), the code is becoming more complex than I'd like.
Possible Solutions
I could work with sub classes, that is, have an abstract
Carclass that's extended byCorvetteandClunker, but then I have the problem of using aCarsobject (because I can't make a collection of something that can't be instantiated). See EDIT below.Using an enum (such as
CarKind) seemingly requires several messy switch statements:- to populate the
speedfield of each car - to create
Carobjects from theCarsclass - etc.
- to populate the
How You Can Help
I'm looking for a solution that allows a single Cars class to contain every Car object. I don't want different collections (like Corvettes, Clunkers). I'm also looking for a solution that allows the creation of Car objects based on the attributes of an individual car kind... as previously mentioned, creating a new Car of kind Corvette would result in a speed of 0.9. There should be no other way to specify a car's speed.
Is there a best practice in this situation? Have I made the example clear enough?
Thanks.
EDIT: The reason I don't want a collection of abstract Car objects is because the point of the Cars collection is to create and manipulate Car objects, regardless of their kinds. Car being abstract seems to complicate this. If you think this is the best solution, please answer accordingly.