CSC/ECE 517 Fall 2010/ch1 25 ag: Difference between revisions
Line 31: | Line 31: | ||
= What is Multiple Inheritance = | = What is Multiple Inheritance = | ||
When a class inherits from more than one class i.e., a child class having more than one parent class, is called multiple inheritance. | When a class inherits from more than one class i.e., a child class having more than one parent class, is called multiple inheritance. Though this feature offers more flexibility, it seem to overwhelm most of the developer, so some of the object oriented language designer decided not to support Multiple Inheritance. Java and C# are some of the most famous language which don't support multiple inheritance. We need careful design to take proper advantage of Multiple inheritance, otherwise you might end up in spaghetti code, with classes inheritancing from multiple classes. | ||
Example: | Example: |
Revision as of 17:58, 18 September 2010
Advantage and Disadvantage of Multiple Inheritance
What is Inheritance?
Inheritance is one of important attribute of Object Oriented Languages. Using Inheritance a class can reuse code defined in another class. The advantage of this approach is that, we can have an hierarchy of Inheritance and write all generic code in the parent class and add only specific functions in the child classes.
Example:
class ElectricAppliance { public void on() { ... } public void off() { ... } }
class TempControlAppliance : public ElectricAppliance { public void increaseTemp() { .. } public void decreaseTemp() { .. } }
class Heater : public TempControlAppliance { public void heat() { .. } }
class Cooler : public TempControlAppliance { public void cool() { .. } }
If we don't have inheritance, we might have to duplicate all the functions in both Heater and Cooler class. Inheritance is very important to achieve DRY (Don't Repeat Yourself). In the above class hierarchy, TempControlAppliance is super (parent) class for both Cooler and Heater subclass (child).
What is Multiple Inheritance
When a class inherits from more than one class i.e., a child class having more than one parent class, is called multiple inheritance. Though this feature offers more flexibility, it seem to overwhelm most of the developer, so some of the object oriented language designer decided not to support Multiple Inheritance. Java and C# are some of the most famous language which don't support multiple inheritance. We need careful design to take proper advantage of Multiple inheritance, otherwise you might end up in spaghetti code, with classes inheritancing from multiple classes.
Example: Building upon the above example, let us say we have a new device called Air Conditioner which can both heat and cool air. We might have a new class called AirConditioner as follows:
class AirConditioner : public Heater, public Cooler { public void setThresholdTemperature(int temp) { ... } }