views:

59

answers:

2

I have multiple kinds of an object, say Car for example.

Do I have each kind in an inherited class/subclass of Car?

Do I place these under a cartype namespace so as not to mess up the main namespace?

Then later when I need an array of cars, should I declare it as var currentCars():Car or var currentCars():Object? Would the former support any subclass of Car?

+1  A: 

You can have an inifinite number of classes inheriting from your Car class as long as you don't have overriden methods that conflict.

As for namespaces, I usually put the classes that inherit from another one in the same namespace, not sure if not being in the same namespace works though.

Oh and when you need an array, you declare it just like any other data type.

You see, when you declare a class Car you create a data type Car.

So when you need to declare an array of cars, you go like this:

var currentCars():Car
Felipe Fiali
+5  A: 

Specific answers are difficult because they really depend on the particulars of your problem space, but in general you would use subclasses of Car if all kinds of Car shared some functionality. E.g.:

public class Car {
    public void Start() { }
}

And then you could have different types of Car:

public class Sedan : Car {
    public void OpenAllFourDoors() { }
}

public class Coupe : Car {
    public void OpenAllTwoDoors() { }
}

You don't generally need to put the class hierarchy into its own namespace, there are other sets of guidance for namespace definitions. Typically, expect namespaces to take the form of something like CompanyName.ProductName.ModuleName or something similar.

Later, when you need an array (or, more commonly, a collection) of cars, you would create a collection of Car. When you grab a reference from this collection, though, you won't be able to OpenAllFourDoors or OpenAllTwoDoors because you won't know which subclass of Car you're working with.

(Apologies for C#-centric syntax)

Greg D
Can't I keep a "kind" property within each subclass (with a default value per subclass) to know which subclass it is? .. and whats the difference between a Collection and an Array?
Jenko
@Jeremy Rudd: You can, but that's generally poor form. Take advantage of virtual dispatch to eliminate the "kind" property, otherwise you're defeating one of the primary motivations of the class hierarchy. E.g., put `OpenAllDoors()` on the base `Car` class and then let each implementation determine how to open all the doors.
Greg D
In most OO languages I've used, an Array is a language construct used to hold a series of objects. A collection (of which there are many different sorts) is a more formal data structure with understood performance characteristics and interfaces. E.g., a Linked List is a type of collection.
Greg D