CSC/ECE 517 Fall 2012/ch1b 1w46 sm
Subclassing
Subclassing
Subclassing is a principle of creating a specialization(subclass/ [1]) of a base class(superclass/ parent class) by inheriting the methods and instance data from the base class.
Subclassing is one of the significant features of OO programming, which greatly increases the reusability of classes and also minimizes duplication of code. A subclass usually inherits some properties from a super class. Inheritance is a design principle in object oriented languages like Java. The reason behind inheritance is to reuse the code of existing objects or establish a subtype from an object. This greatly improves the efficiency and makes the code more readable as methods which are written only once can be used by a lot of subclasses. A superclass consists of common features that can be extended over subclasses. Superclass and subclass are commonly called base and derived class. The relationship between a subclass and superclass can be represented by a simple UML diagram as shown below.
Advantages of Subclassing
Method Overriding
This feature mainly depends on the object oriented language but it’s advantage can be exploited by using subclasses. It permits a class to replace the implementation of a method that has been inherited. This process is termed as overriding. Overriding requires the compiler to perform some sort of optimization so that the right method is invoked. C++ uses virtual pointer along with vtables to remember which function has overridden it’s definition inherited from the base class. In C#, overriding of a method should be specified by the program itself. The following example illustrates method overriding in C++.
#include <iostream.h> class Base { public : virtual void show() { cout << "In Base"; } }; class Derived:public Base { public : void show() { cout << "In Derived"; } }; void main() { Base b; Derived d; Base *b2 = new Derived(); b.show(); d.show(); b2->show(); }
Reusability
By creating subclass, the code of the base class can be reused in many situations. This gives subclass the freedom to create more specialized functions. It can use the base class methods to create these special functions. Apart from avoiding code duplication, this helps in decreasing the file size thereby saving some memory space.
For instance, we maybe programming animal characteristics but there is a special class of animals called mammals. Mammals display some specialized functions which can be defined in the subclass. As per Liskov Substitution principle which is discussed later, mammals obey the constraints enforced by the animal class and hence this kind of implementation avoids code duplication.
Why do we Subclass?
- Code reuse
- Specialization: A subclass can define new methods it's superclass does not handle.
- Method Overriding: An overridding method can either have minor modifications or be completely changed from its parent class' implementation.