DotNetBlocks

Things on DotNet, programming, and other useless stuff

OOP inheritance vs. OOP composition

Object oriented programing inheritance creates a “is a” relationship with the parent class. One example of this is if we create a class called Food. Food contains the following properties: mattertype, weight, fat, carbohydrates and protein. Now create a subclass called Buffalo_Wing which inherits the parent class food. This new relationship takes the form of “is a” because Buffalo_Wing is a food that contains mattertype, weight, fat, carbohydrates and protein. One way to check this relationship is to ask yourself “Is Buffalo_Wing a Food?”. If you answer yes, then your relationship is correct.  In addition the subclass also adds the property sauce. When you try and use a new instance of the class Buffalo_Wing you will have access to the following properties: mattertype, weight, fat, carbohydrates, protein, and sauce.

Object oriented programing composition creates a “has a” relationship with other class. We can create a class called Meal with the following properties: MealType, Buffalo_Wing(), Fries(),Beverage(), Pizza_Slice(). This class creates an array of instances of the class Buffalo_Wing because the meal may contain more than one Buffalo_Wing. To check if this relationship is correct, you can say “My meal has a chance of consisting of Buffalo_Wings?”.  If this statement is true then the relationship is correct. This is also true for Fries, Beverage, and Pizza_Slice.

In my personal opinion I think that both methods are very good, but I also think that the fact of object oriented programingInheritance can override the base parent class or classes is a very valuable tool which cannot be ignored. This allows the child classes to alter the methods of the parent class to as they need them in the instance of the child class.

Comments are closed