teacher
Sign in

Inheritance and Polymorphism

Reuse behaviour with subclasses, let one call do different things through dynamic dispatch, and avoid the C++ slicing trap.

30 min3 interactive

Inheritance

Inheritance lets a class (the subclass, derived class or child) take the fields and methods of another (the superclass, base class or parent) and add or change things. It models an is-a relationship: a Square is a Shape.

  • Overriding: a subclass supplies its own version of a parent's method (same name and parameters).
  • Overloading: several methods with the same name but different parameters in one class. This is not polymorphism; the compiler picks one by looking at argument types.
JavaC++
Extend a classclass B extends Aclass B : public A
Methods overridable by defaultYes (unless final)No, must be marked virtual
Mark an override@Override (annotation)override (keyword)
Abstract methodabstract int area();virtual int area() const = 0;
Multiple parentsInterfaces onlyAllowed for any class
1 of 6