OOP: Class Inheritance

Please see my other Object-Oriented Programming (OOP) articles.

Leveraging Inheritance for Code-Reuse & Maintainability

As demonstrated by my Object-Oriented Programming (OOP) article, in addition to Encapsulation, Polymorphism (link), and Composition (link), OOP provides a powerful mechanism for reusing code and easier maintainability by allowing common class attributes and behaviors to be defined within a parent class, then inherited by one or more child classes.

I will demonstrate this principle with a common scenario which involves two types of classes- an employee and a supervisor.
Both employee types share common attributes such as names and both need to take a vacation (behavior). In addition, the supervisor manages employees and the system needs to return number of subordinates.

First, I’ll define all attributes (data) and methods (behavior) in the employee class. By defining common elements in a class, it may be reused by other classes which share similar characteristics, reducing duplicate code and making it more maintainable as there is only one location for changes.

Next, I’ll create a class for supervisor which inherits the employee class, allowing the supervisor class to reuse employee attributes and methods.

Now, I’ll instantiate a Supervisor object which uses its parent method and object method.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s