I need to make a collection of several different classes. In my mind, the sub classes inherit from a more general super class. So I have the class SuperClass, which currently has a member variable o of Object type, which will take a single instance of one of the subclasses class SubClassA and class SubClassB. SubClassA and SubClassB have some things in common, such as the need to create database tables to hold descriptions of themselves. Therefore, each subclass needs to have a method CreateDatabaseTables(). Currently I have a collection of SuperClass instances, each of them containing an Object o which can be one of several classes that I will not know at compile time. Maybe this isn’t the best way to do this…
My question is, when I iterate over the collection, will I be able to call something like
for (int i = 0; i < superClassArray.size; i++)
{
superClassInstance[i].o.CreateDatabaseTables();
}
without having to cast Object o into one of the SubClasses?
Or have I gooned up the whole thing and I am just plain doing it wrong? Is this concept called inheritance, or is it something else? I don’t think it is inheritance because I do not intend to write a CreateDatabaseTables() method in the SuperClass. Each class will have to have its own method.
You’re not using inheritance, but composition.
You don’t need members in your base class:
And simply call the overriden method on the base class: