Introduction to ada 95
Download
1 / 82

introduction to ada 95 - PowerPoint PPT Presentation


  • 303 Views
  • Updated On :

Introduction to Ada 95. Joyce L Tokar, PhD [email protected] Course Outline . History and Overview Large Scale View of Ada Conventional Features Packages and Overloading System Programming Features Object Oriented Features Real-Time Features Tools and Environments .

Related searches for introduction to ada 95

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'introduction to ada 95' - Jimmy


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Course outline l.jpg
Course Outline

  • History and Overview

  • Large Scale View of Ada

  • Conventional Features

  • Packages and Overloading

  • System Programming Features

  • Object Oriented Features

  • Real-Time Features

  • Tools and Environments


Afternoon session l.jpg
Afternoon Session

  • Look into the support for Systems programming, Real-Time programming, and Object-Oriented programming.

  • Look at the tools and environments available for developing Ada applications.


Ada 95 highlights l.jpg
Ada 95 Highlights

  • Upward Consistent

    • Six new reserved words:

      • abstract, aliased, protected, requeue, tagged, until

    • 8-bit Character Type

    • Small efficiency improvements

  • Building on Ada 83 concepts

    • Private and derived types for data abstraction and OOP.

    • Subprogram and entries for user-defined and protected operations.

    • Packages for structuring the program library and distributed applications.


Ada 95 highlights5 l.jpg
Ada 95 Highlights

  • Systems Programming Support

    • Child library units

    • Interfaces

  • Real-Time Programming Enhancements

    • Protected types for data-oriented synchronization

    • Requeue of an entry caller

    • Asynchronous transfer of control

  • Object-Oriented Features

    • Tagged type extension

    • User-defined type classes and dispatching operations

    • User-defined initialization, finalization, and assignment


Systems programming l.jpg

Ada

95

Systems Programming

  • Hierarchical Libraries

  • Generics

  • Interfacing to other languages



Program libraries l.jpg
Program Libraries

  • The Ada program library brings important benefits by extending the strong typing across the boundaries between separately compiled units.

  • The flat nature of the Ada 83 library gave problems of visibility control. It prevented two library packages from sharing a full view of a private type. Resulting packages became large and monolithic maintenance nightmares.

  • A more flexible and hierarchical structure was necessary.


Systems programming enhancements l.jpg
Systems Programming Enhancements

  • Subsystem facilities.

  • Facilities to “hide” auxiliary units within subsystems.

  • Subsystem interfaces that involve private types.

  • Signification reduction in recompilation.

  • Support for interfacing to other systems.


Hierarchical libraries10 l.jpg
Hierarchical Libraries

  • Library unit may have child library units.

  • Share private parts amongst children.

  • Allows disciplined type extension of private types.

  • Allows for incremental development.

  • Clients with only those units they need directly.

  • Clients are recompiled only when those units are changed.

  • Direct support for subsystem concept.


Hierarchical libraries11 l.jpg
Hierarchical Libraries

package Complex_Numbers is

type Complex is private;

function "+"(X,Y : Complex) return Complex;

... -- similar functions for "-", "*", and "/"

function Cartesian_to_Complex

(Real, Imag : Float) return Complex;

function Real_Part(X : Complex) return Float;

function Imag_Part(X : Complex) return Float;

private

...

end Complex_Numbers;


With clause l.jpg
“with” clause

  • with clause -- used to give visibility to a library unit.

  • This allows you to access components of Complex_Numbers using dot notation (formally known as selected component notation).

  • The with clause gives visibility to anything found in the specification of the withed unit.

with Complex_Numbers;

procedure CALCULATE is

My_Complex : Complex_Numbers.Complex;

begin

My_Complex := Complex_Numbers.Cartesian_to_Complex(3.2, -1.0);

end CALCULATE;


Use clause l.jpg
“use” clause

  • use clause -- used to give direct visibility into a library unit.

  • Requires the corresponding withclause first.

  • This allows access to the components within the Complex_Numbers library unit without dot notation.

with Complex_Numbers; use Complex_Numbers;

procedure CALCULATE is

My_Complex : Complex;

begin

My_Complex := Cartesian_to_Complex(3.2, -1.0);

end CALCULATE;


Child library l.jpg
Child Library

package Complex_Numbers.Polar is

function Polar2Complex(R, Theta : Float)

return Complex;

function "abs"(X : Complex) return Float;

function ARG(X : Complex) return Float;

end Complex_Numbers.Polar;


Hierarchical libraries15 l.jpg
Hierarchical Libraries

with Complex_Numbers.Polar;

-- implies with Complex_Numbers;

package Client1 is

R : Float := 0.0;

Angle : Float := 45.0;

P1 : Complex_Numbers.Complex :=

Complex_Numbers.Polar.Polar2Complex(R, Angle);

end Client1;


Hierarchical libraries16 l.jpg
Hierarchical Libraries

with Complex_Numbers.Polar;

use Complex_Numbers;

-- Child name Polar and components of the specification

-- of Complex_Numbers are directly visible.

package Client1 is

R : Float := 0.0;

Angle : Float := 45.0;

P1 : Complex := Polar.Polar2Complex(R, Angle);

end Client1;


Hierarchical libraries17 l.jpg
Hierarchical Libraries

with Complex_Numbers.Polar;

use Complex_Numbers;

-- Child name Polar and components of the specification of

-- Complex_Numbers are directly visible.

package Client1 is

use Polar;

-- Components of the child Polar are directly visible.

R : Float := 0.0;

Angle : Float := 45.0;

P1 : Complex := Polar2Complex(R, Angle);

end Client1;


Private children l.jpg
Private Children

  • A private child is typically used to add additional functionality to the parent.

  • They prevent the parent from growing too large.

  • Private children can only be seen by the bodies of their ancestor.

  • Typically, they are withed by the body of their parent.

  • A private child is never visible outside of the tree rooted at the parent.

  • In essence, the first private child down a long chain hides anything below it from outside view.


Private children19 l.jpg
Private Children

private package Complex_Numbers.Hidden_Operations is

--Types and procedures in this package can be used

--in the body of Complex_Numbers.

end Complex_Numbers.Hidden_Operations;


Visibility rules l.jpg
Visibility Rules

  • Declarations in the parent visible part are visible throughout specifications and bodies of children.

  • Declarations in the parent private part are visible in the private part and body of public children and throughout private children specifications and bodies; but not in public children specification parts.

  • Public children can be made visible anywhere with a with clause.

  • Private children can be made visible from the specifications or bodies of other private descendants of the parent, or from the parent body.

  • Child packages and nested packages may not have the same identifier as a name.


Friends don t let friends use use l.jpg
Friends don’t let friendsuse use

  • Leads to problems during maintenance.

  • Makes debugging difficult.

  • Pollutes the name space.

use


Summary of hierarchical libraries l.jpg
Summary of Hierarchical Libraries

  • Child library units support hierarchical structuring of a large system into subsystems

  • Recompilation of clients is minimized by modularizing a large subsystem interface into visible child units.

  • Recompilation of the implementation of a subsystem is minimized by modularizing into private child units.

  • A package can be effectively extended by adding a new visible child, without disturbing existing clients.


Children of generics l.jpg
Children of Generics

  • Generic packages can have children.

  • The child of a generic package must itself be a generic unit.

  • The child generic unit can only be instantiated in two ways:

    • Inside the generic body of its parent;

    • As a child of an instance of its parent.

  • A child of an instance must itself be an instance.


Children of generics24 l.jpg
Children of Generics

generic

type Floating is digits <>;

package Generic_Complex_Numbers is

type Complex is private;

function "+" (X, Y : Complex) return Complex;

private

type Complex is

record

Real : Floating;

Imag : Floating;

end record;

end Generic_Complex_Numbers;


Children of generics25 l.jpg
Children of Generics

generic

package Generic_Complex_Numbers.Cartesian is

function Construct (R, I : Floating) return Complex;

function Real_Part (X : Complex) return Floating;

function Imaginary_Part (X : Complex) return Floating;

end Generic_Complex_Numbers.Cartesian;


Children of generics26 l.jpg
Children of Generics

with Generic_Complex_Numbers;

with Generic_Complex_Numbers.Cartesian;

procedure D_to_A is

type My_Float is new Float digits 6;

package My_Complex_Numbers is

new Generic_Complex_Numbers( My_Float );

package My_Cartesian_Numbers is

new My_Complex_Numbers.Cartesian;

Y : My_Float := 0.0;

X : My_Float := 34.3;

C : My_Complex_Numbers.Complex :=

My_Cartesian_Numbers.Construct( X, Y );


Generics and hierarchical libraries l.jpg
Generics and HierarchicalLibraries

  • A library unit cannot be compiled until other library units mentioned in its with clause are entered into the library.

  • A subunit cannot be compiled until its parent body is entered into the library.

  • A body cannot be compiled until the specification of its parent is entered into the library.

  • A child cannot be compiled until the specification of its parent is entered into the library.

  • A package specification and body form a single declarative region.


Generics and hierarchical libraries28 l.jpg
Generics and Hierarchical Libraries

  • A library package can only have a body if it needs one to satisfy other language rules.

  • Do not attempt to redefine Standard.

  • Renaming is not text substitution.

  • A library unit could not be renamed as another library unit in Ada 83/87.

  • A subprogram body could not be provided by renaming in Ada 83/87.


Other language interfaces l.jpg
Other Language Interfaces

  • Ability to reference (or call) Ada entities from other languages and to reference (or call) entities from Ada code.

    • Set of new pragmas: Export, Import, Convention

      • Export entities created by the Ada program to other programs.

      • Import entities created by other programs into the Ada program.

      • Convention specifies the calling conventions or data layouts.

    • Call-back/call-out via dispatching operations on tagged types.

    • Call-back via subprogram access

  • package Interfaces


Import interface l.jpg
Import Interface

type Matrix is array (1..100, 1..100) of Integer;

pragma Convention( ZZ_Fortran, Matrix );

-- Matrix is to be laid-out in conformance with the format that is used

-- by ZZ_Fortran.

Fortran_Matrix : Matrix;

pragma Import( ZZ_Fortran, Fortran_Matrix, Link_Name => “Values” );

-- the object Fortran_Matrix is created by foreign code, where it is

-- called “Values”; no storage will be allocated for its Ada declaration.

function Multiply( A,B : Matrix ) return Matrix;

pragma Import( ZZ_Fortran, Multiply, “_multi” );

-- the body of Multiply is provided by some routine name _multi with

-- ZZ_Fortran calling convention; to be supplied externally.


Access types l.jpg
Access Types

  • Pool-specific access types

  • General access types

  • Access parameters

  • Access discriminants

  • Access to subprograms

  • Storage pool management


Access parameters l.jpg
Access Parameters

procedure Main is

type T is ...;

type A is access all T;

Ref : A;

procedure P( Ptr : access T ) is

begin

...

Ref := A( Ptr ); -- dynamic check on conversion

end P;

X : aliased T;

begin

P( X’Access );

... -- can now manipulate X via Ref

end Main;


Access parameters33 l.jpg
Access Parameters

  • The actual parameter corresponding to an access parameter can be:

    • An access to an aliased object such as X’Access;

    • Another access parameter with the same accessed type;

    • A value of a named access type again with the same accessed type;

    • An allocator.

  • An access parameter can be:

    • Used to provide access to the accessed object by dereferencing;

    • Passed as a parameter to another access parameter;

    • Converted to a named access type.


Access to subprograms l.jpg
Access to Subprograms

type Trig_Function is

access function( F : Float ) return Float;

S,C,T : Trig_Function;

-- these variables can point to any function that has

-- a float as a parameter and returns a float value.

X, Theta : Float;

S := Sin'Access;

C := Cos'Access;

T := Tan'Access;

Theta := Some_Degree;

X := T.all(Theta);

-- As with many uses with access types the .all is not usually

-- required; it would be necessary if there were no parameters.


Call backs l.jpg
Call Backs

type Button is private;

type Action is access procedure(B : in out Button);

procedure Set_Action(B : Button; A : Action);

pragma Import(ANSI_C, Set_Action, ... );

-- some procedure in ANSI_C that expects a reference to

-- a subprogram which will be called from within the foreign

-- code when some event occurs.

procedure My_Action(B : in out Button);

. . .

Set_Action(Some_Button, My_Action’Access);

-- registers the Ada procedure My_Action for call back

-- from foreign code.


Package interfaces l.jpg
package Interfaces

  • Defined in the required annex called Interface to Other Languages

  • Contains declarations of various machine integer types plus shift and rotate functions for modular types.

  • Includes a number of child packages:

    • Interfaces.C

    • Interfaces.C.Strings

    • Interfaces.C.Pointers

    • Interfaces.COBOL

    • Interfaces.Fortran


Classes of ada types l.jpg

Objects are single values

Scalar

Composite

Objects contain components

Protected

Coordinated access to shared data

Tagged

Inheritance and runtime polymorphism

Access

Objects point to other objects & subprograms

Objects are abstract

Private

Objects are parallel processes

Task

Classes of Ada Types

Ada

Types


Improved real time capabilities l.jpg
Improved Real-Time Capabilities

  • More efficient data communication and synchronization.

  • Building blocks to construct common real-time paradigms.

  • More control of task scheduling.


Protected types l.jpg
Protected Types

  • A synchronization mechanism which provides access to shared data without including an additional task.

  • A low-level, real-time building block that may be used to construct common real-time paradigms.

  • Low-level, light weight, data synchronization mechanism.

  • Encapsulation of shared data and access operations.

  • Similar to Conditional Critical Region with Signals.


Protected operations l.jpg
Protected Operations

  • Protected functions provide read-only access to the protected type data components.

  • Protected procedures provide exclusive read-write access to the protected type data components.

  • Protected entries provide exclusive read-write access to the protected type data components with guarded access.


Simple protected type l.jpg
Simple Protected Type

protected type Shared_Data is

function Read return Data_Type;

procedure Write(New_Data : in Data_Type);

private

Data : Data_Type;

end Shared_Data;

Spec

protected body Shared_Data is

function Read return Data_Type is

begin

return Data;

end Read;

procedure Write(New_Data : in Data_Type) is

begin

Data := New_Data;

end Write;

end Shared_Data;

Body


Using protected types l.jpg
Using Protected Types

SD1 : Shared_Data;

SD2 : Shared_Data;

SDA : array( Index_Range ) of Shared_Data;

task body T1 is task body T2 is

… …

beginbegin

… …

D1 := SD1.Read; SD1.Write(D2);

… …

end T1; end T2;


Protected entries two levels of protection l.jpg

Protected Object

The Entry Barriers

Protected EntriesTwo Levels of Protection

  • The entry barrier is used to indicate a change in the state of the protected object; every protected entry must specify an entry barrier.

  • All barriers are examined at the completion of a protected operation that may have changed the state of the protected object; e.g, at the end of a protected procedure or protected entry call.

  • Task's waiting for a protected entry barrier condition to become true are enqueued on the protected entry's queue.


Counting semaphore specification l.jpg
Counting Semaphore Specification

protected type Counting_Semaphore

( Initial_Count : Integer := 1 ) is

entry Acquire; -- "P" Operation

procedure Release; -- "V" Operation

function Current_Count return Integer;

private

Count : Integer := Initial_Count;

end Counting_Semaphore;


Counting semaphore body l.jpg
Counting Semaphore Body

protected body Counting_Semaphore is

entry Acquire when Count > 0 is

-- Suspend until Count > 0, then decrement Count

begin

Count := Count - 1;

end Acquire;

procedure Release is

begin

Count := Count + 1; -- Increment Count

end Release;

function Current_Count return Integer is

begin

return Count; -- return the current value of Count

end Current_Count;

end Counting_Semaphore;


Counting semaphore in use l.jpg
Counting Semaphore in Use

Max_Users : constant := 10; -- Maximum Number of Users of Service

User_Semaphore : Counting_Semaphore ( Max_Users );

procedure Use_Service( P : Param ) is

begin

User_Semaphore.Acquire; -- wait if there are too many Users

begin -- critical region

Perform_Service( P );

exception

when others =>

-- Always release the semaphore for the next user.

User_Semaphore.Release;

raise;

end; -- critical region

User_Semaphore.Release; -- Release the semaphore for the next user.

end Use_Service;


Buffer manager l.jpg

protected Buffer is

entry Put( X : Item );

entry Get( Z : out Item );

private

Full : Boolean := False;

Y : Item;

end Buffer;

protected body Buffer is

entry Put( X : Item ) when not Full is

begin

Y := X; Full := True;

end;

entry Get( Z : out Item ) when Full is

begin

Z := Y; Full := False;

end;

end Buffer;

Buffer Manager


Buffer manager in use l.jpg
Buffer Manager in Use

Buffer

Producer

Consumer

Put(X)

Get(X)

task body Producer is

X : Item;

begin

loop

-- Produce X

Buffer.Put( X );

end loop;

end Producer;

task body Consumer is

Z : Item;

begin

loop

Buffer.Get( Z );

-- Consume Z

end loop;

end Consumer;


Asynchronous transfer of control l.jpg
Asynchronous Transfer of Control

  • Allows a sequence of statement to be interrupted and then abandoned after some event.

  • Used for mode change, time bounded computations, user-initiated interrupts, etc.

  • Triggering alternative can be either the completion of an entry call, or the expiration of a delay statement.

select triggering_alternative;then abort abortable_part;end select;


Atc in use l.jpg

Event Processing

loop

select

Keyboard_Await_Cancel;

Put_Line( “Canceled” );

then abort

-- This code is abortable

Put( “->” );

Get_Command( Command, Last );

Do_Command( Command( 1..Last ) );

end select;

end loop;

Timeout

-- Cancel computations when a

-- timeout occurs

select

delay 1.5;

then abort

Complex_Function(FIR_Range);

end select;

ATC in Use


Requeue statement l.jpg
Requeue Statement

  • Allows a caller to be "requeued" in the same or some other queue for later processing.

  • Without the with abort option, the requeued entry is protected against cancellation.

requeue Entry_Name [with abort];


Delay statements l.jpg

delay delay_expression;

delay Sleep_Period;

Resume_Work;

Relative delay statement will continue execution after waiting (at least) the designated period of time.

delay until delay_expression;

delay until Alarm_Time;

Resume_Work;

Delay until will resume execution at the designated time.

The untildoes not provide a guaranteed delay interval, but it does prevent inaccuracies due to swapping out between the “delay interval calculation”.

Delay Statements


Annexes l.jpg
Annexes

  • Systems Programming Annex

  • Real-Time Annex

  • Distribution Annex

  • Numerics Annex

  • Safety and Security Annex


Systems programming annex l.jpg
Systems Programming Annex

  • Specifies a number of low-level features including:

    • in-line machine instructions,

    • interrupt handling,

    • shared variable access

    • task identification.

    • Atomic pragma (indivisible read/writes)

    • Volatile pragma (bypasses cache memory)

  • Pre-requisite to the Real-Time Systems Annex


Real time systems annex l.jpg
Real-Time Systems Annex

  • Includes pragmas that allow you to tailor:

    • scheduling of parallel processes

    • priorities of parallel processes

    • queueing protocols for entry calls

    • ceiling-locking protocols

  • Must include documentation specifying:

    • time it takes to actually abort a task on both single and multi-processor systems

    • time it takes to process an asynchronous select

  • Includes a Monotonic time package.

  • Includes low-level asynchronous and synchronous task control options.


Distributed systems annex l.jpg
Distributed Systems Annex

  • Includes features that give you ability to:

    • communicate between partitions running on different processing and/or storage nodes.

    • categorize library units as to how they are used (determines if/when it can be distributed).

    • set up a remote library that is used for remote procedure calls (RPCS), using both static binding and dynamic binding of remote procedures

    • make an asynchronous procedure call (which returns without waiting for completion).


Numerics annex l.jpg
Numerics Annex

  • Accuracy requirements for floating and fixed point arithmetic, accuracy requirements for the various predefined packages including...

    Ada.Numerics

    Generic_Complex_Types

    Generic_Complex_Elementary_Functions

    Complex_types

    Long_Complex_Types

    Complex_Elementary_Functions

    Long_Complex_Elementary_Functions

  • Floating point is defined in terms of model numbers as they relate to the implemented properties. There are no safe numbers. The model is in terms of the exponent of the machine.


Safety and security annex l.jpg
Safety and Security Annex

  • This Annex address requirements for systems that are safety critical or have security constraints. It provides facilities and specifies documentation requirements that relate to several needs:

    • Predicting program execution

    • Reviewing of object code - pragma Reviewable

    • Restricting language constructs whose usage might interfere with program reliability.

  • pragma Normalize_Scalars – ensures that all otherwise uninitialized objects have an initial value.


Pragma reviewable l.jpg
pragma Reviewable

  • Directs the compiler to generate object code that can be independently validated.

  • The following information must be produced:

    • Where compiler-generated run-time checks remain

    • Identification of any construct that is certain to fail

    • Where run-time support routines are implicitly invoked

    • For each scalar, either “Initialized” or “Possibly uninitialized”

    • An object code listing with machine instructions, offsets, and source code correspondence

    • Identification of each construct with possible erroneous execution

    • Order of library elaboration


Other annexes l.jpg
Other Annexes

  • Required Annexes:

    • Predefined Language Environment

    • Obsolescent Features

  • Other domain specific annexes:

    • Information Systems


Predefined language annex l.jpg
Predefined Language Annex

  • Contains packages that support:

    • Predefined Identifiers

    • Character Handling

    • String Handling

    • Numerical Functions

      • Basic math functions

      • General Trig/Log functions

    • Random Number Generation

      • Discrete

      • Continuous


Input output l.jpg
Input/Output

  • Ada supports many different types of predefined IO.

  • Each type has its’ own package with supporting functions and procedures:

    • Ada.Sequential_IO

    • Ada.Direct_IO

    • Ada.Wide_Text_IO

    • Ada.Streams.Stream_IO

    • Ada.Text_IO


Information systems annex l.jpg
Information Systems Annex

  • This Annex provides a set of of facilities relevant to Information Systems programming. These fall into several categories:

    • The package Decimal which declares a set of constants defining the implementation’s capacity for decimal types, and a generic package for decimal division.

    • The child package Text_IO.Pictures, which supports formatted and localized output of decimal data, based on picture string.


Obsolescent features annex l.jpg
Obsolescent Features Annex

  • This section contains descriptions of features of the language that worked under Ada 83, but are no longer needed and not recommended under Ada 95.

  • Most good programmers will not find any of the “obsolescent features” a problem. However, there are a few changes to Ada 95 that would require a lot of “nit-picking” changes. There are a few predefined renaming clauses to prevent you from having to edit all of your old programs. However, your new programs should use the correct methods.

    For example:

    with Ada.Text_IO;

    package Text_IO renames Ada.Text_IO;


What is oop l.jpg
What is OOP?

  • There are a variety of definitions available generally based on the language being used to implement the OO model. In general, one can say that OOP is:

  • Programming around the concept of objects by defining:

    • A type

    • Operations upon the type (methods)

    • With the flexibility to dynamically

    • Extend a type with new components and operations.

    • Identify a type at run time and manipulate values of several specific types – polymorphism

    • Choose an operation at run time.


Object oriented methods l.jpg
Object Oriented Methods

  • OO is closely allied to reusability. It’s main advantage is that systems can be separated into logical components, allowing better modeling of the problem world. OO creates better abstractions.

  • In addition, OO systems can be extended, rather than modified, to add functionality. This prevents disturbing existing software, eliminating the risk of introducing errors.


Support for the phases of object oriented development l.jpg

OOP

OOD

OORA

Support for the Phases of Object Oriented Development

  • OORA

    • Packaging

    • Abstraction & Encapsulation

    • Parallel Processing

  • OOD

    • Packaging & Child Packages

    • Strong Typing

    • Enumeration Types

    • Parallel Processing

  • OOP

    • Inheritance

    • Polymorphism (Dispatching)

    • Tasking


High level view of oop in ada 95 l.jpg
High Level View of OOP in Ada 95

  • Type Extension – the ability to define one type in terms of the other especially as an extensions of another – tagged types and child library units.

  • Inheritance – the ability for such an extended type to inherit the primitive operations of its parent and also to replace and add to such operations -- tagged types.

  • Polymorphism – the ability to distinguish the specific type of an object at runtime from among several types and in particular to select an operations according to the specific type – class wide types & type extension.

  • Late binding – the ability to select an operation at run time – dispatching based on run time choice of type of parameters and result type.


Tagged type l.jpg
Tagged Type

type Rectangle is tagged

record

Length : Float := 0.0;

Width : Float := 0.0;

end record;

-- Operations for inheritance are now defined

-- Example: Rectangles have a defined perimeter, and

-- children derived from Rectangle will have Perimeter.

function Perimeter (R : in Rectangle ) return Float is

begin

return 2.0 * (R.Length +R.Width);

end Perimeter;


Tagged type inheritance l.jpg
Tagged Type -- Inheritance

type Cuboid is new Rectangle with

record

Height : Float := 0.0;

end record;

function Perimeter (C : in Cuboid ) return Float is

begin

return Perimeter (Rectangle(C)) * 2.0 + ( 4.0 * C.Height);

end Perimeter;

  • Cuboid inherits Perimeter from Rectangle (technically, Perimeter is a primitive operation). The function will have to be updated for the new type (Perimeter is defined differently for cubes!).

  • To do this, you need to override the operation. One way to do this is to write a new Perimeter. A better way it to base the new Perimeter on the parent class operation.


Abstract types subprograms l.jpg
Abstract Types & Subprograms

  • Purpose of an abstract type is to provide a common foundation upon which useful types can be built by derivation.

  • An abstract subprogram is a place holder for an operation to be provided (it does not have a body).

  • An abstract subprogram MUST be overridden for EACH subclass.

-- Baseline package used to serve as root of inheritance tree

package Vehicle_Package is

type Vehicle is abstract tagged null record;

procedure Start (Item : in out Vehicle) is abstract;

end Vehicle_Package;


Abstract types subprograms72 l.jpg
Abstract Types & Subprograms

type Train is new Vehicle with

record

passengers : Integer;

end Train;

My_Train : Train; -- ILLEGAL

  • We can’t yet declare an object of Train. Why? Because we haven't filled in the abstract parts declared in it’s parent. We have completed the abstract record, but still need to define procedure Start for the Train.

type Train is new Vehicle with

record

passengers : Integer;

end Train;

procedure Start (Item : in out Train) is ....

My_Train : Train;


Abstract types l.jpg
Abstract Types

type Planes is abstract new Vehicle with

record

Wingspan : Some_Type;

end Planes;

function Runway_Needed_To_Land

(Item : Planes) return Feet is abstract;

  • You cannot declare a variable of type Planes (it is abstract), so you must derive from it. However, when you derive a new type from Planes, you must also override the function Runway_Needed_To_Land.


Inheritance chains l.jpg
Inheritance Chains

  • All records that derive from a tagged record are implicitly tagged.

  • Each inherited record inherits all fields and operations from its parent, creating an inheritance chain.

  • If you use an operation on a inherited type that is not explicitly written for that type, then the chain is searched towards the root. The first instance of the operation will apply.

  • You can even add abstract records at a child level, allowing you to selectively create the exact fields and inheritance desired.


Class wide programming t class l.jpg
Class-Wide ProgrammingT’Class

Vehicle’Class

Vehicle

  • With each tagged type there is an associated type ’Class.

  • The values of this ’Class type include all derived types.

  • Any derived type may be converted to the type ’Class.

Trains

Automobiles

Planes

Planes’Class

Jet Propeller Helicopters


Polymorphism l.jpg
Polymorphism

  • The introduction of Class-Wide types provide for dynamic polymorphism.

  • Each tagged type T has an associated type denoted by T’Class. T’Class is comprised of the union of all the types in the tree of derived types rooted at T.

  • Each value of a class wide type has a tag which identifies its particular type from other types in the tree of types at run time.

  • The type T’Class is treated as an indefinite type (like an unconstrained array type). Therefore all objects declared to be of type T’Class must be initialized with a specific type.

  • A formal parameter can be of a class wide type and the actual parameter can then be on any specific type in the class.


Class wide programming dynamic dispatching l.jpg
Class-wide ProgrammingDynamic Dispatching

--class-wide value as parameter

procedure Move_All ( Item : in out Vehicle’Class) is

...

begin

Start (Item); -- dispatch according to tag

...

end Move_All;

  • The procedure Move_All is a class-wide operation, since any variable in the Vehicle hierarchy can be passed to it.

  • Start, however, is defined for each type within the Vehicle hierarchy. Depending on the type of Item, a different Start will be called. During runtime, the specific type of Item is known, but it is not known at compile time. The runtime system must dispatch to the correct procedure call.


Static binding l.jpg
Static Binding

-- class-wide value as parameter

procedure Move_All ( Item : in out Vehicle’Class) is

...

begin

...

Start (Item); -- dispatch according to tag -- dynamic dispatch

Start (Jet(Item)); -- static call to the Start for Jet. This call will

-- fail at run time if Item is not a member of

-- the Jet hierarchy.

...

end Move_All;


Class wide programming using pointers l.jpg
Class-Wide ProgrammingUsing Pointers

-- Vehicles held as a heterogeneous list using an access type.

type Vehicle_Ptr is access all Vehicle’Class;

-- Control routine can manipulate the vehicles directly from the list.

procedure Move_All is

Next : Vehicle_Ptr;

begin

...

Next := Some_Vehicle; -- Get next vehicle

...

Start (Next.all); -- Dispatch to appropriate Handle

… -- Note the de-referencing of pointer

end Move_All;


Controlled types l.jpg
Controlled Types

package Ada.Finalization is

type Controlled is abstract tagged private;

procedure Initialize (Object: in out Controlled);

procedure Adjust (Object: in out Controlled);

procedure Finalize (Object: in out Controlled);

  • A type derived from Controlled can have an user-defined Adjust, Finalize, and Initialize routines. Every time an object of this type is assigned, released (via exiting scope or freeing up a pointer) or created, the appropriate routines will be called.


Questions l.jpg

Ada

95

QUESTIONS


Thank you l.jpg

Thank You!

Joyce L Tokar, PhD

Pyrrhus Software

PO Box 1352

Phoenix, AZ 85001-1352

USA1-480-951-1019

1-480-607-3762 (FAX)

[email protected]

www.pyrrhusoft.com


ad