ada Packages Parent-Child Relationship


Example

As a way of subdividing Ada programs, packages may have so-called children. These can be packages, too. A child package has a special privilege: it can see the declarations in the parent package's private part. One typical use of this special visibility is when forming a hierarchy of derived types in object oriented programming.

package Orders is
   type Fruit is (Banana, Orange, Pear);
   type Money is delta 0.01 digits 6;
   
   type Bill is tagged private;

   procedure Add
     (Slip   : in out Bill;
      Kind   : in     Fruit;
      Amount : in     Natural);
   
   function How_Much (Slip : Bill) return Money;
   
   procedure Pay
     (Ordered : in out Bill;
      Giving  : in     Money);
   
private
   type Bill is tagged record
      --  ...
      Sum : Money := 0.0;
   end record;
end Orders;

Any Ada unit that is headed by with Orders; can declare objects of type Bill and then call operations Add, How_Much, and Pay. It does not, however, see the components of Bill, nor even of Orders.Bill, since the full type definition is hidden in the private part of Orders. The full definition is not hidden form child packages, though. This visibility facilitates type extension if needed. If a type is declared in the child package as derived from Bill, then this inheriting type can manipulate Bill's components directly.

package Orders.From_Home is
   type Address is new String (1 .. 120);
   
   type Ordered_By_Phone is new Bill with private;
   
   procedure Deliver
     (Ordered : in out Ordered_By_Phone;
      Place   : in     Address);

private
   type Ordered_By_Phone is new Bill with
      record
         Delivered : Boolean := False;
         To        : Address;
      end record;
end Orders.From_Home;

Orders.From_Home is a child package of Orders. Type Ordered_By_Phone is derived from Bill and includes its record component Sum.