Inheritance lets us define new types as extensions of existing types; these new types inherit all the operations of the types they extend. The new types are termed `children' or `derived types', while the types extended are usually called `parents' or `base types.' Inherited operations can be overridden with new definitions of those operations. Derived types can also add new operations that apply only to them, not their base types.
In Ada 95 terminology, types that can have parents or children are termed ``tagged types'', and have the keyword ``tagged'' as part of their definition.
This is probably best shown through an example (this example is taken from the Ada Rationale). Let's imagine that we're writing a program that must deal with a number of different Alerts with different priorities.
We could define a general type called an `Alert', and then define some useful operations applicable to any Alert (let's call them Display, Handle, and Log). We could then create two children of Alert, one called Low_Alert (for an Alert with low priority) and one called Medium_Alert (for an Alert with medium priority). Medium_Alerts will have more information - an Action_Officer who must deal with the alert.
We can then create yet another type, High_Alert, as a child of Medium_Alert, and add information on when it should ring an alarm. Since it's a child of Medium_Alert, High_Alert would inherit the Action_Officer defined by Medium_Alert. Here's how the hierarchy might look pictorially:
Alert * Low_Alert * Medium_Alert o High_Alert
And here's how the package specification could look:
with Calendar, People; package Alert_System is type Alert is tagged record Time_Of_Arrival : Calendar.Time; Message : Text; end record; procedure Display(A : in Alert); procedure Handle(A : in out Alert); procedure Log(A : in Alert); type Low_Alert is new Alert with null record; type Medium_Alert is new Alert with record Action_Officer : People.Person; end record; -- Override default Handle operation for Medium_Alert procedure Handle(MA : in out Medium_Alert); type High_Alert is new Medium_Alert with record Ring_Alarm_At : Calendar.Time; end record; procedure Handle(HA : in out High_Alert); procedure Set_Alarm(HA : in High_Alert); end Alert_System;
Go back to the previous section
Go up to the outline of lesson 7
David A. Wheeler (wheeler@ida.org)