I wrote this during my first semester at MATC and the exercise helped me to to think more object oriented. I hope other code newbies might find this useful.
Inheritance is a feature of object-oriented programming which allows for a class to inherit attributes and behaviors of another class. Inheritance is integral to good object oriented design. Through the use of inheritance code can be reused.
Microsoft gives good guidelines for when to implement inheritance. When the relationship between subclass and superclass can best be described as “is a” rather than a “has a”. When you have to apply the same class and methods to different data types. When you want to make global changes through changing a base class.
The way inheritance works is by creating a class which will function as a superclass or parent class which will pass on properties and methods to child classes or subclasses. So for example we could create an Animal parent class which will have certain attributes and behavior to move, to eat. Creating the subclasses of animal we might have mammal, bird, and crustacean subclasses which would inherit all of the qualities of the animal class. Mammal could then act as a parent class to the class Human. The result of this design is a hierarchical structuring.
There are different types of inheritance which all have to do with the relationships between the parent and child class. In single inheritance all of the child classes inherit from one parent class. In cases of multiple inheritance the child class inherits from more than one parent class. Multilevel inheritance happens when a chain occurs where a sub class inherits from a superclass and then in turn acts as a parent class for another sub class.
Considering the different types of inheritance brings about the question of inheritance conflicts. The main conflict that arises when using inheritance is when two parent classes define the same property in the child class. This is where the concept of overriding comes into play when the programmer
explicitly defines what the properties definition is.
Here is an interesting video from the clean code talks for those who have time to go into more depth. I found his discussion of replacing if's and switch statements with subclasses to be very useful in furthering my understanding of inheritance. Check it out and let me know what you think in the comments.
explicitly defines what the properties definition is.
No comments:
Post a Comment