Summary
This first example of a complete program pulls together various aspects of the type Object and its descendants which were discussed in Chapter 3. This opening description is followed by the text of the program and then some notes on specific points.
The program is in two phases. It first reads in the dimensions of a number of objects and then computes and prints out a table of their properties.
The root package Geometry contains the abstract type Object together with various abstract operations. The function MI is the moment of inertia of the object about its centre (see Exercise 3.3(5)). The function Name returns a string describing the type of the object. Each of the concrete types is then declared in its own child package.
The child package Geometry.Circles declares the type Circle which is derived from the abstract type Object and has one additional component, Radius. It also declares concrete functions Area, MI and Name which implement the corresponding abstract operations of the root type Object.
The child packages Geometry.Points, Geometry.Triangles, and Geometry.Squares then similarly declare types Point, Triangle, and Square with appropriate concrete functions.
There are also a number of other child packages containing related material. The package Geometry.Magic contains the class wide functions Moment and MO; Moment gives the vertical moment about the origin whereas MO gives the moment of inertia about the origin. The package Geometry.Lists contains entities for defining and manipulating lists of objects. The package Geometry.IO contains functions for reading the properties of the various types of objects; each such function returns a pointer to a newly created object.
There are then two library subprograms to do the two major phases of activities, namely Build_List and Tabulate_Properties. Finally the main subprogram Magic_Moments essentially just calls these two other library subprograms.
package Geometry is
type Object is abstract tagged
record
X_Coord: Float;
Y_Coord: Float;
end record;
function Distance(O: Object) return Float;
function Area(O: Object) return Float is abstract;
function MI(O: Object) return Float is abstract;
function Name(O: Object) return String is abstract;
end;
with Ada.Numerics.Elementary_Functions;
use Ada.Numerics.Elementary_Functions;
package body Geometry is
function Distance(O: Object) return Float is
begin
return Sqrt(O.X_Coord**2 + O.Y_Coord**2);
end Distance;
end Geometry;
- Type
- Chapter
- Information
- Programming in Ada 2012 , pp. 59 - 62Publisher: Cambridge University PressPrint publication year: 2014