Object Oriented Programming/Subclasses

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Subclasses, also referred to as derived classes, heir classes, or child classes, are classes that inherit one or more language entities from another class/classes. While their may be some minor differences in how class inheritance works between different languages, generally, the subclass automatically inherits the instance variables and member functions of it's superclasses or parent classes. [1] From the wikipedia page on inheritance, you can see how a subclass is generally defined. [2]

class SubClass: visibility SuperClass
{
    // subclass members
};

The colon at the end of 'Subclass' means that it inherits from the "SuperClass" at the end.

Non-subclassable classes[edit | edit source]

Some languages have non-subclassable classes. These are classes that have no subclasses. Non-subclassable classes can be created by adding certain class modifiers to the class declaration. After being created the non-subclassable classes will restrict reusability of code, especially when source code is not accessiable. A few examples of class modifiers that creat Non-subclassable classes include Java's 'final' keyword or C#'s 'sealed' keyword. These modifiers are added to the class declaration before the class keyword and identifier declaration.

Since a non-subclassable class has no subclasses, references or pointers to objects of that class can be easily deduced to be referencing instances of that class and not instances of subclasses or superclasses since a non-subclassable class has no subclasses, and an instance to a superclass would be violating the type system. Early binding(static dispatch) can also be used instead of late binding(dynamic dispatch) due to the exact type of the object referenced being known before execution.

References[edit | edit source]

  1. https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)
  2. Herbert Schildt (2003). The complete reference C++. Tata McGraw Hill Education Private Limited. p. 417. ISBN 978-0-07-053246-5.