Inheritance and Polymorphism
Reuse behaviour with subclasses, let one call do different things through dynamic dispatch, and avoid the C++ slicing trap.
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.
| Java | C++ | |
|---|---|---|
| Extend a class | class B extends A | class B : public A |
| Methods overridable by default | Yes (unless final) | No, must be marked virtual |
| Mark an override | @Override (annotation) | override (keyword) |
| Abstract method | abstract int area(); | virtual int area() const = 0; |
| Multiple parents | Interfaces only | Allowed for any class |
1 of 6