Understanding OO Essentials: Classes, Inheritance, Polymorphism and Interfaces
So far, classes and objects seem like little more than just a fancy way to bundle code together, like an advanced include module, for example. But there is one important ingredient to object oriented programming that completely sets it apart: inheritance.
Inheritance is the ability to start with an existing class and use it as a starting point for creating another class. So what? You can copy and paste code from a module and do the same thing, right? But suppose you've used a base module as the starting point for several others. Then you make a change to that base module. In order for that change to be reflected in all those other modules, you have to go and make the change there, too. This is actually a very common scenario and a major cause for inconsistencies and bugs in all kinds of applications.
And inheritance works for multiple generations as well. That is, you can inherit from a parent to create a child. Then you can inherit from the child to create a grandchild. Any changes made to either the parent or child is reflected in the grandchild.
As you might imagine, this means that you have the ability to create intricate and complex structures or inheritance hierarchies. Inheritance is a powerful feature. But its the kind of power that's easy to abuse and significantly more difficult to use well.
What's the best strategy for creating an inheritance hierarchy? The first rule is to think in terms of generalization. The higher the class is in the hierarchy, the more general and abstract it should be. The lower you get in the class hierarchy, the more concrete and specific the classes should be.
Here's an example. Suppose you decide to reengineer your EmpClass to take advantage of inheritance. Your highest-level class might be Employee. It would contain properties like Name and Phone. Inherited from Employee might be a class called SalariedEmployee. Properties of this class would include the Name and Phone that was inherited from Employee, but it would also include a property called Salary. At the same time you might have another class that inherits from Employee called HourlyEmployee. In addition to the items that were inherited from the Employee class, this class may contain properties like Hours and Rate.
Here's what it would look like in Visual Basic .NET.
Class Employee Public Name As String Public Phone As StringEnd ClassClass SalariedEmployee Inherits Employee Public Salary As LongEnd ClassClass HourlyEmployee Inherits Employee Public Hours As Integer Public Rate As SingleEnd Class
Once you've created this hierarchy, you can use the child classes as if the parent properties were directly apart of them.
Dim Emp1 As SalariedEmployeeDim Emp2 As HourlyEmployeeEmp1 = New SalariedEmployeeEmp2 = New HourlyEmployeeEmp1.Name = "Fred Smith"Emp1.Phone = "555-1331"Emp1.Salary = 26000Emp2.Name = "Bob Jones"Emp2.Phone = "555-1331"Emp2.Hours = 40Emp2.Rate = 6.50
Page 2 of 4