Inheritance vs varying instances?
c#, java, oop
Solution
If you have a few properties that are shared by all cars (or methods that act on the object), and then unique properties (or methods) for each make/model, then you'd want to use inheritance. Otherwise, just varying instances are fine.
Let's just say you want these properties for all cars:
- Make
- Model
- Year
- Number of doors
In this case, you wouldn't want to create a class hierarchy, because it doesn't buy you anything.
Instead, if you had two "types" of cars: regular and race-car, and only the race-car could enable Nitrous Oxide (presumably a method that does this), you'd want a Car class, with RegularCar and RaceCar inheriting from it.
If you're just afraid of having to pass the same parameters to your constructor all the time, you can create static methods that call the constructor on your behalf. This is known as the Factory method pattern.
PS: my example really just came off the top of my head. But I hope you get the idea of what I'm trying to say :)
Problem
If I were modelling various brands of cars would I use an inheritance hierarchy, or just varying constructor parameters? What is the general rule for whether to relate objects using inheritance, or just by re-using the same class? For cars I could just do something like new Car("Porsche","991","3.8") or I could have an overall abstract Car superclass, with abstract subclass manufacturers like "Porsche" and then possibly a class for each model of Porsche?