A, Cover Pag€ 93-26 Anoouncement Broad Agency

advertisement
A, CoverPag€
93-26
BroadAgencyAnoouncement
AND ADA
ENGINEERING
CURFJCULUMDBVEIOPIVGNTIN SOFTWARB
Categoryl and3 Eoposal
of ObjectTitlc: CuldculuEandlbxtbookDovslopEcntUsiry Ade9x for theTbaching
Proposal
OricntedConcepts
TechnicalPointofcootacr
HatbertL. Dershem
Scienco
of ComPutor
DepartEent
ItopeCoUege
IIoUan4MI49422-8000
(616)39+7510
denhe@cs.hoPe.odu
(Onleavo1993-4at thofo owingaddrsss)
DopartEentof Computr[Science
Unibd StabsAit ForceAcademy
USAFAcadonY,C0 80840
QLg)472-3590
a.af.mil
hdershe!@cs.usaf
AdminisbativoPoht of Contacl
Eliot A' Tbnis
Dcanfor thoNanral Scionces
HopoColl€ge
IIoUrnd MI49422-8000
(616\X9+7714
uni@PhYrics.hopc.edu
TOPECO1IEOE
DEANFORNATURALsCIENCES
November9, 1993
BAA #93-26
ARPA/SISTO
3701NonhFairfaxDrivo
Allir,ltan, VA 22203- 1714
TO WHOMIT MAY CONCERN:
thatI endo$etheideasatd concepts
andexcitement
Fesentedby
It is with sigdficartenthusiasm
theDepartnentof ComputerScicnceatHopcCollogein thisprcposalentitled"Cuniculumand
usingAda9X for theTcachingof ObjoctOrientedconcepts."
Toxtbookdsvelopment
to take
in thisproposalis timciy8ndinnovativo.Ii will allowstudents
Theprogxamdescribed
in out curriculumthoughAda
prcgramming
concepts
of objectoriented8ndsdvanced
advantsge
of the
andit is unde$tanding
is welcomingof students
9X. TheFoposedcuricularendeavor
bdngwith them,espcciallyin contrastto otheravailable
thatstudonts
varianceiin backgrounds
"whercthey8re"8nd
!o meetstudents
It is designed
environments.
objectorientcdprogramming
helpstudents
to achievetheirfullcstpotentialof understanding.
HopoCollegeis committedto suppolttttisprogramin cvcryway.My oflicowill work wifi Prosucccss.
fgssorDershcmin a coodinatedfashionto insu!€progremmatic
Wearethankfulfor theopportunityto submitthispmposalandwc look forwardto developinga
in computer
for futurEsuccess
\,,/iththeloolsnecpssary
vital proglamthatwill ptovidestudents
science.
Sincerely,
{^ez;*
a./i/^;
Efliot A. Tanis
Doatlfor theNaturalSciences
pEArE
8OX9000
IASTl2THSTREET/P.9
CENTER/ls
SCTENCE
4
F
AX
616-394-7923
616
394-771
IGAN
49
422-9OOA
/
D.
MICH
I
HOTLAN
B. Descriptionof the Project
Statementof Work
Scope
programming
languages
andobject-oriThisFoject will rcsultin theEdesignof two courses,
In additio&theprojectdirecontedprograoming,sothattheyarobasedon thcAcla9X language.
programming
it
includes
languages
a chaptetortAda9X under
textbooksothat
tor will rcvisehis
paradigm,andwill cvise thouseof Adaasanillustrationof theimperative
theobject-oriented
paradigms
madcitr Ada9X.
to rcflert changcs
andconcurrent
TechnicalApproach
2,700.The
Hop€Crllegeis a four-yeartiberalafisinstitutionwith enmllmentof approximately
collegchashada compute!sciencedepsrtnentsince1974.Thedcpartmont
Fpsendyconsistsof
in
Science,
The
hold
Ph.D.
degr€cs
Computer
tbreeof whom
fourfi.rll-timefacultymembcrs,
graduatos
between10and15majorscachyear.
d€partment
programming
is cunsntlytaughth twoplacesin theHopoCollagoComputet
Object-olionted
is
two wee,ks
in
couse,approximatcly
Scicnc.e
curriculum.First, $e progranmirylanguages
'Ihe
paradigm. languages
SmalltalkandC+f arcinuoducedin
devotedto thoobject-oriented
accordance
with theFesortationof dle iopicin thetextbookwhichis coauthottdby thc Project
Direato![1].
placethatobjoct-orientod
Thesecond
Fogranmingin foundis in a opics cousewhichis offer€d
cou$€
followhg thePlogammingLarguagcscourseandwhichhasthePmgramningLanguagcs
Thelanguage
usedin thiscouNein thepasthasbe€nC++.
asa prerequisite.
to illusEatetheimperaThcfust cditionof thetextbookmcntioncdobovcusesAdaass languag€
just
andwill bcpublishedin
tiveparadigm.
A secondeditionof thistextbmkhas beencompleted
1994.In thateditiontheconcumntparadigmhasbc€nadd€dandAdais slsouscd8s&primary
paradip, both
of thcobjcct-orientcd
illustadol of thatparsdig[ In dle textbook'sdiscussion
In th€sccondedition,a chapteris
smaltalk aralC+r asillustsations.
editionsusethelanguages
devotedto eachof thes€laqguages.
prograrmingis oneof fte mostimportantandpopularlopicsin ComputerSciObject-Oriented
is C++.Ada9X
C).nrendy,
thelanguage
of choicoin mostof iodusty andacademe
cncetoday.
capashowsthepromisethatit mightradicallychangcthis si$atio! by pmvidingobject-oriented
structuedlanguage,In
udcr for thisto happen,
effectiveeducatioal
bilitieswithina weU-designed
EaterialsDustbeprcducodwhichpesenttheobject-olienbdmodelin themntextof theAda9X
language.
Thcpurpose
of thisprojectis to incorporat€
Ada9X asa Fototypelanguage
for theobject-oriprogramming
etrt€dparadigm
irrtotheprogramming
language
andobject-oriented
courses.
The
biggesrhirdraoceto doirg thisin thenearfutulewill befte lackof textbookswhichusoAda9X
thisproblemby Fovidpamdigm.ThisFojoct is inEndedto addrcss
to toachthoobject-odented
ing a timelyrcvisionof a toxtbookalrcadyon themarket.
SpecificThsks
T'hte€majortasksareploposedio thisproje.ct:
lcxtbookdcsctibingAda-gxasit appliesto the
1.Writinga newchapterof theDetshem/Jippirg
.Ihis
paradlgn"
ch&plcrwi11befor ioclusionir thenextcditionof this tcxtbook.
object-ori-cnted
2.RcvisingthcdiscussionofAdsintheDetshcm/JippingtoxtinElstiontotheimpelstiYeand
in Ada9X.
to rcfleclthechsngos
concurentparadigms
countcsatHope
atd Objcct4dent€dPlogramming
thekograoming Lsnguages
3. Rcclcsign
Collcgeto basedremon Ada9X.
TtmoFrarneofBffort
July,1994
bxtbook
Chapterfor Dersh€ny'Jipping
DrafrAd89X Object-Orienrcd
8tHoPeCollegeusingncn'chapt€r
1994 TeachProgranningL€nguages
August-Decembsr,
usingit
€xp€dence
P€visochsptcraccordilgto tho
June,1995
Mate fnal Dvkion !o Object€rienbdAda9X chapt€rfG
submission
b publisher
July,1995
Makerevisionrto imperativeandcolcurcnt scctionsof D€rstteE/
in Ads9X andsondtevisions!o
to t!fl€ct chang€s
Jippingtor(tbook
oublishor
i995
August-Docomber,
TeachObject'OionedProgranningcoursoatllope Collegeusing
Ada9x
May,1996
Preparcryllabusad othernat€ri8lsfromObiect-Oriantcd
andfinal prcjectrcpor1
coursefor diss€mirution
Programming
Summaryof AnticipatedResults
Thispmjertwill havetwo majorFsults.Thcf$t will beNr€visionto thctcxtbookProgramming
andlifodelsth&tu'i[ rcsuttin its thid €dition.Thisrevisionwill containa
Languages:
Structures
Ada9X asit Epr€s€nts
thatpararcw chapterutrdertheobject-ode edparadigmthatdiscusses
of Adaundertheimperativeandconcuqcntpardigm.It will alsohavotevisions!o fre Eeatment
in Ada9X..
adigm$rorcflectthechanges
Editionof dleDersheD/Jipping
tcxtbookis givenbelowwith
of theSecond
TheTableof Contents
thatwill bomadeasa rssultof thisp!oje4t.Sectionswhich
annotttionsindicatingthechanges
4
newobject-oriappearin boldwi bemodifiedto rcflectchalgosin AdaJoundin-Ada9X.The
e'ritedchapterwitt appearbetweenchaptcrs14and15asi[dicatedin ths table'
Lalguages
I. Ovowiewof Programming
1.IntroductionandOverview
tanguage?
1.1Whatisa Programming
1.2Why studyproganminglanguages?
1 3A bdefhistoryof Foglamminglanguages
2. PEliminaryConcopts
2.1 Syntaxspecificatiol
2.2Semarticsspociication
Eanslation
2.3Languago
charactodstics
design
2.4Language
2.5Choiceof language
rI. ImperativeModel
3, Overviewof ImperativeModel
3.1DatatYpes8ndbindings
3.2Executionunitsand scopeof binding
3.3Contr0lstructures
4. Datasseresates
models
4,ibaia aggregate
4.2Arrays
4,3Strings
4.4Records
4,5Files
4.6Set6
5. ProceduralAbstraction
5,1Pmceduresassbshactions
5.2Proceduredefinition8nd invocrtion
5.3Proceduteenvironment
5.4ParameXers
5.5Vsluertturning Procedures
5.6Overloading
5.7Comutines
5.8Pmceduresin Ada
5.9Exceptions
5.10Exceptionsin Ada
6. DataAbstraction
6.1Abstractdatatypes
6.3Encapsulation
6,4Parameterization
6.5Monitors
6.6Dataabstractionin Ada
-C
7. ExampleLanguage
7.1PhilosophyandaPP,roach
7.2Informationbinding
7.3Contol sfuctues
7.4Dataaggregatss
7.5Prccedualabstraction
7.6Dataabstractiol
?.7Commonlibraryfunctions
- Modula-2
Language
Example
8.
andapPloach
8.1PhilosophY
8.2Inforoationbhding
8.3Controlstructures
8.4Dataagglogates
8.5PlocedunlabsEaction
8,6Dataabstsaction
Itr. FunctionalModel
9. Overvicwof FunctionalMod€l
9.l Functions
9.2FunctionalProgramming
9.3Functiomllanguages
9.4FP:a pulefurctionallargusSe
9.5Bvaluationof fuctional languagcs
- A Functionsl-Odented
Language
10.Scheme
10.1Basiccompononts
10.2Functiondefnitior
10.3ExamDles
of Sch€Eoto FP
10.4Comp-arison
l,anguage
Typed
Functional
ML
A
i1.
ML
of
11.1Featules
1I .2BxamDI€s
of ML o FP
11.3Comp-arison
ry. hgic-OdentedModEl
12.Ovcrviowof l-gic-Ori€ntcdlvlodcl
spdel
to logiclanguage
12.1Introductiotr
12.2A pue logiclanguage
querYlanguages
12.3Databsse
13.Prolog A logic-Oriont€dLanguage
13.1Syntaxof Prolog
13.2Non-logicmodelfeaturcsof Prolog
13.3Examplcprogta6sin holog
Model
V. Object-Orientod
Model
14.Overviowof Object-Oriened
of objoctorierted Model
14.1components
Modol
14.2hopertiesof Object-Orieuted
An
example
14.3
with imperativomodel
14.4Compadson
lchapt€r on Ada 9X \f,ill beadd€dhercl
6
Laoguage
15.Smalltalk- anObject-Oriented
15,lOvervigw
15.2Smalltalksyrtax
15.3Classhierarchy
15.4Abstlactclasses
in Smalltalk
15.5ADexamDle
language
Object-Oriented
a
Hybdd
16.C++
16.I Overview
of C++
16.2Componorts
16.3An exanplein C++
VI. DisEibut€dfarallelModel
Model
17.Ovorvicwof thoDistibuted/Parallel
defr[ition
17.1Process
of Processes
17.2Invocation
Data
shaing
17.3
comrrumcauon
17.4Interprocess
17.5Svnchronization
Unitsin Ada
18.Concurre'nt
18.1Processdefinition
18.2Processinvocation
18.3Datasharing
18.4Interpr0cesscommunicstion
18.5Synchronization
18.6Examplesin Adg
19.Occam- a ParallolLanguago
defirition
19.1Process
19.2Plocossinvocation
19.3Datashadng
communication
19.4lllteryrocess
19.5Synchronization
in Octam
19.6Examptes
coursc
Programming
Thesecondtesultof this plojc{t wiU bc th€d€signof anObject-Oricnrcd
part
rcpolt
on this
as
s
of
the
its
submision
in
to
basedon Ada9X. It is altticipatedthat sddition
project,a paperdescribingthecoursewill besubmitrcdto theSIGCSEBu[etin.
ProprietaryClaims
The PrcjectDkector will rctain propdetaryrights to all modificationsof the textbook' Ptogramto DARPA in the
ming Languages:Structut€sandModels.Ile will include an acknowledgernent
part of this
as
a
book.Ho will haveno othe! plopdet!ry rights to ary othermatedalcreated
project.
C. Sunmary of Deliverables
tcxtbookoo Ada9X asanexampleof tbeObjcct-Ori'
1.A newchaptetof theDcrshery'Jipping
entedparadigmtextbookto t!ficct
2. A list of rcvisionsto beincludrdin tlrcThtd Bditionof DcrsheEy'Jipplng
pdadigms'
to Ada9X withi! thci4crativo andconcullnt
changes
on Ada9X'
3. A syllabusandsamplcprojccbfor 8nobjcct'cicntedprogranningcoune^b8xcd
to tlr SIGCSBBuuetir
rn"*Gu uo zuttoittia i tt rcn or a papu suitablefs submis$ion
8
D. summary of Scheduleand Mil€stones
Date
July 1994
Activity
A rcugh dreft of an Ads 9X object-orientedchapt€rfor Do$hen/Jippitrg will
bo comPloted.
be
Aug-Dec, 1994 Ploglammhg languagecourse$using tll9 draft of the Ada 9X chapterwill
taughtat fioPe College(by Dcnhem)'
revise
Juno-July,1995 De$hom will makcfinal rvisions totheAd' 9X object-oricntsdchapter'
the imperativeandconcunentmodtl discussionsof thc tcxtbookto rcflect
changisin Ada 9X, arutdosignan object'oricnredcoursebasedon Ada 9x' He
studcntwho will cod€8td test
wil 6'easisted by a half-tine undergraduate
ptognms 8ndwork exerciscs.
Aug-Dcc, 1995 Dershemwill tcacbthe Objcctoriontcd coulsc usingAd! 9x at Hope Couoge
May, 1996
Do$hcE will Pr€psl! fual Eport 8nddeliverablesfot this poject'
Key Personnel
(CuriculumVitaein App€tdix)
HcrbcttL. Dctrshem
four monthsof fuU-timecffort,dir€ctingall sctivitiesabove
Efon expended:
dudngSplingSenest€r'1995)
Assistant(to beselect€d
Undagraduate
two tnonthsof half-tine effott
Efron exDsnded:
9
Work
Retated
E. Previous
ProfessolDeNhomhasbeenactiveincomputelscicncecurriculuEdevelopmentfolmorc
His tust activitvwasin thedesignof a counethatcombinedthetoachingof
,h-;;il;;;
by a grantftomthe
scicnce[1]. His workon thatprojectwassupported
,,*lr,i"t uii
"o-po*t
an-drpsultedin thepublic&tionof a laboraorymanualfor uscin
s;i";;;i;""dation
il;;;
sucha course[2].
--to
of I Eodularapproach
moi"r*rbarrr,"m wasalsofundedby NsF for rhedeveloprbcnt
prcject'two modulesonpmbthetpachingof introductorycomputerscie;e [3]' As a pan of this
lemsolvingwereproduced[41t5].
Evidcnceof
Pmfe;or Do$hemhastsught,workedwith, andwinen aboutAdaextcnsively' publicawhichis duefor
rr,i* ir trr"ii*tuoot t"ferencedprcviouslypl andis secondedition[8]
8t-theUnitedStales
1993-94
tfreProjectoire;oa whileon leaveduring
t"i i^ fsga. I"
"ddiri"n,
*Uf teachatourseon object-oriecdpro€runmingurhg Ada9X dudngthe
eit norceecaO".y,
infom0tionto assistin thoinitiaThis wiu providehim with backsmund
i;il;;;;
i;;;
tion
-- of thisFojoct.
A fundedprojcctto
p.f"ssor De$hemis F€s€ndycompletingworkona DARPi" uOAii6"ti,
Thisprojcctwill becompletcdin
coursoto usoth€Adalanguage'
rcdrsignthedatastructures
June,1994.
for Und€rExp€d€nces
is alsothc PrincipalInvcstigatorfor a Research
Dershem
Professor
for
six underfunds
ThisFovides
fundedby theNation;lscicnceFoundation'
sraduetes
Drogram
L a-ot"t"ut"h in iach of thrcesummcrs,1992,1993'and1994'
iluOuu"t
-*il;;;";-D";t"m
andin theactiviticsof the
hasalsobepnactivcin cuniculumdevclopmcnt
Cto"p on ComputerScionceBducation(SICCSE)of thoAClvt'He seweds proSo.nJi"*ti
-ni"of thatsymposium
[6]'
andeditedttreproceedings
.rt"i*iift" rSs8SIGCSESymposium
'
Depad'
science
Computel
C'ollege
Thisoroiectwiu utilize6e stN netwo* of theHope
-*,. ifrii nlwott i, describein dctailin theAppendix'Pt€s€ntlywc run MeridianAd8on that
projectswitl dependupor thoavailneiwo*. Thevorsionof Acla9X thatwe usefor 11'"proposed
abilityofcompil€rsat thotime.
Bibliogsphy
of 1972
ttl., A coulseotrcomputing8ndstatisticsfor socialsciance'Proceedings
Ul Dershem,
1n2'
inThctJndergradwtcCurricul*' ArlarLt4-GA'
Conf*erci on Comptuers
for ElanenfiryS,a,isticJ,Comprcss,Inc"1979'
[2] Derrhen,IlL., Cozpier Exercises
Bu etin'
i3i D*ft"., H.L., ,q,modutarinuoduclorycomputorsciencccoursc,EIGCSE
Feb,1981.
13(1):177-181,
Boslon'Inc"
ProblemSolving'Bfuhause!
t4l De!sh;, H.L., UMAPMod e477: Conrputer
1981.
Problemso'vi'g, Birkhauser
[5] D€lshem,H.L., UMAPModule478:IteratiorrandComputer
Inc,,1981.
Boston,
Slmposium'Assof,iaTechnical
of theNineteenthSIGCSE
[6] Dolshem,H.L. (ed.], Proceedings
tion for ComputingMachinery1988.
pl Dershem,
H.L. and IWrng,M.J., Prograwdnglanguages:ModclsandStuctwes,Wad1990.
swolthPublishingComParY,
Second
laquhges: ModelsandStructures,
Progranvning
M.J.,
H.L. and lippirlg,
[8] Dershem,
Edirroz,PWSKentPublishingCo.,1994.[to appear]
10
F. CostBreakdown
textbookdescribirg
Task1: Writs a newchapterfor theThfudEditionof theDershemAipping
Paradigm'
Ada9X asit aPpliosto theobject-odented
Tlvomonthsfull-timeeffolt by plojectdircctor(July,1994ard June1995)
1995)- ro plojoctcost
Offeringof courseusingmaterials(August-December,
student(June1995)
OnemJnthhalf-tine asiistarceby undergaduate
TotatCost:$17,034
textin relationto imp€ntiveandconcurontparadigmto
Tbsk2: Revisercxtin Delshcm/Jipping
in Ada9X
refloctchangos
1995)- no projectcost
Draftcdby projectdiector duringoffcringof coutse(Arlgust-December'
Oncmonthfull-timeeffolt by ptojoctdircctor(July,1995)
studeot(July'1995)
by unddgraduote
Onsmonthhalf-timeassistance
Total Cost:$9,090
Progammingcoutses8tHope
8ndObject-Oriented
Languagcs
ofPtogramming
Thsk3: Rodesign
Collegeto basethemon Ada9X'
1995)- no Foject cost
Cou$edosignandoffedngby proje{tdircctot(August'Decomber,
Onemonttriott-C-e effo; bi ;mje{t dircclorto wdteup coulseandprojcctresult!(M&y'1996)
Total Cost:$8,340
BudgetSummary
July,
' ' 1994
yearsalary)
ProjoctDirectot'sSalary(1/9academic
PrcicctDir€cto!'sBencfits(20%of salary)
$ 6'620
$ 1,324
June-July,
' 1995
yearsalary)
Projc,ctDtector's S8l8ry(2/9acadomic
ProjectDircctot'sBcnefits(207oof salary)
stipend
Half-timestudentassistant
$13'900
$ 2,?80
$ 1,500
May,
' 1996
yearsalary)
ProjectDiroclor'sSalsry(U9 acadomic
ProjectDi$tor's Benefits(20%of salary)
$ 6'950
$ 1'390
$34'464
TotalBudget
1l
CURRICULMITTAE
HerbertL. Dersbem
Educstion:
B.S.Urive$ityof Dayton,1965
PurdueUniversity,1967
M,S.(ComputerScience)
PuducUniYersity,1969
Science)
Ph.D.(Computer
ExDeriefice:
4
1969-197
HopeCollege,AssistantProfessor,
1974-1981
Profosso!,
Associate
Plofessor,1981-Prosent
19?6-prescnt
Cbairof ComDuF!ScienceDepartrncnt,
Scientist,1977-1978
VisitingRosearch
OakRidgeNationalLaboratorios,
1982-1983
Progran,VisitingProfessor,
Bostontnivelsity Ovorseas
Visitinghofesso!'1993-1994
Distinguished
UnitedStatesAir ForceAcademy,
HonorsandAwards:
NDEAFsUowPudusUniversity,1965-1968
Fctlow PurducUnivorsfty'19681969
HoneywellCorporation
ProjectCOMP(IIoAwadc€'DarmrouthCollege'1972
NAS{ASEE Summe.Fellow,GoddardSpaceFlightC€nter,1976
UniversitiesSummerFelloq 19?7
OakRidgeAssociated
Grants:
Co-dircclor"lnuoductionof thoComputslin thoStatisticsC\llriculum NSFOmce
Activities'1971-1973
"
of Computing
Director,"A ModularApFoachto theIntroductoryCoursein ComputorSciencc"'
NSFhcal CourseImploverDntProgram'1978-1980
Lsborabryfot usein TeachingStatistics",NSF
Co-Dbector,
"A Microcomputer
SciontincEquiprrnt hogrsm' 19791980
Instrucdonal
NSF
in Suppoltof Comput€!Scionc€Research",
Dirccto!,"CSNETMember$hip
RUIkogram,1987-1990
hogram", NSFREUProgffr\
Rcsearch
Undergraduate
Dircctor,"ComputerScience
1992-1994
in theTbachingof Data
andVisualization
Director,"Useof Ada,Laboratories,
Grant'
andDiscreteMathcdntics",DARPACurdculumDovolopDont
Structutes
1993-1994
Publicstions
: (23 total,ttFsepeltinentto thisFoject listedin Bibliogaphy)
Othermajorsourcesof Jrpport;None
Relatedprcposalspendizg.'None
t2
App€ndix - Description of Hope College Computer Networks
Computer ScienceDepartment Sun Nehrork
Machine/Part
Peripherals
Sun4660
Sun4/470
(2) Sun4/40s
(6) Sua4/60s
32MB memory,2.0CB disk, 14,400baudmodem
32MB memory669MB disk
U./16MB memory500MBdisk,3.5"floppy
16MB mcmory500M8disk,3.5"floppy,GX graphics
copflxessor
16MB memory,500M8disk,3.5"floPPy
32 MB memory,500M8disk,3.5"floppy
1.0GB disk,3.5"floppy
32 MB rDemory,
unitrhousedin Sun4/470
Parallclprocessing
(3)Sun4/65s
10s
(2) SunSPARCstatior
(1) SuIlSPARCstation
10
(32)INMOStansputers
of
l,ab softwaFincludesstandaddisEibutcdSunosrunixsoftwa&.ThisincludcsI distsibution
packwhichis a versionof theX windowingsystem.In addition,sevelal
Sun'sOpeowindows,
from YariousvendorsincludingFranrMaker,SunGI6' SUnPHIGS'
ageshavebeonpurchased
deccntor 8ndObjec€entenSunPC'and
Sunlink DNI Dtchst supportsoftware,Ccn@rline
for theTlanspubrs.
softwarcat! avail,ablc
8nddovclopEont
AdobeTtansc{ipt.INMOSlanguages
includingTEX,EMACS,andDEOIEtutilThelabusesseveralpublicdomainsoftwatEpEckagcs
ities.
M€rit
provideaccess
to thcIntffnotthrougha coll€ge-owned
Tholab'ssoftwarEandhardware
routingequipment.
YAX Network
Thecollegeownstwo VAX 4000syslcmswhichservetheentirecampusconmunityfot acaftom elevenlocations
This sysbmis accessible
dcmic,adninisradve,andlibraryapplications,
In
on ca.mpus
whichhaves totalof lr|4 stationsthetaroPubliclyavailablefor student8cc€s8.
across
the
campus.
addition,ther,earenany otlpr trminals avsilablein officesandlaboratories
A widsrelectiorof softwarcis svailsbleon theVAX syrtemsincludingtheV€ldixVADSsystem
of Adasoftwarodevelopmenr
PC Network
Thetris a Novolllocalareanetnorkin thebuildingcomplexwh€t€thisprcjectwill beconducted
though a common6le s€rvct.Tkelty€ight of thosesysbmsnl€
49 486systems
th8tconnects
thatincludcsoneHPLaserjetm prinrcr,andeprojectionsysEm.
locatcdin a computerclassroom
13
A
Ilope College
Department oJ Computer Science
Hollanrd, Michig an 4 I 4 2 2 -I OOO
(676) 395-7570
May 13,1997
Mike Shumate
NCTAMS-LANT
9456FourthAvenue,Suite2m
BldgV53,N9/M
NavalAir Station
Norfolk,VA 235I I -2199
E@PY
DearMike,
Enclosedyou will fnd the Final Reportfor Air Forc€Contract#F29601-94-K-0033,Cuniculum
andTextbookDevelopmentUsing Ada 9X for the Teachingof Object-OrientedConcepts.A complete setof deliverablesis alsoenclosed.
It hasbeena pleasurcworking with you andI greadyappreciatethe funding providcdunderthis
contract.Pleaselet me know if you ncedanyfunher informatioD,
Sincerely,
HerbertL. Dershem,Chair
Final Report
Air ForceContract# F29601-94-K-0033
Curriculum and Textbook Developnent Using Ada 9X for the Teaching of
Object.Oriented Concepts
Ilerbert L. Dershem
Departmentof ComputerScience
Hope College
Holland. MI 49422-9000
May13,1997
Summaryof Activities
The table below indicatesthe activitiesthat werecarriedout with supportfrom this conkact:
July,1995
Reviewcdthe secondedition of the textbook,Programminglanguages:
Structuresand Modelsby DershemandJipping to updateall Ada referencasto reflcct the changesmadein Ada 95.
Conductedthoroughreview of featuresof Ada 95 with assistancefrom
undergraduate
studentsAndrewVanPemisandManuelCalderon.These
studentswere suppo{todby a NationalScicnceFoundationgrant under
program(CDA 9423943)
the ResearchExperiencesfor Undergraduales
This study includeda thoroughanalysisof tho objoct-orientedfeatures
of Ada 95. The final reportof this studyis include.dasa deliverable.
Designeda coursein Object-Olientedprogrammingwith a significant
portion devotedto Ada 95.
August-Dccombat Taughtthe courseCSCI 495, Object-OrientedProgrammingat Hope
1995
Collegeusing Ada 95. The syllabusfor this courseis includedasa deliverable.
June-July,1996
DraftEda new Chapterfor tlle proposedThirdEAiuon of Programming
Languages:Structuresand Modcls.This chapteris includedasa deliverable.
August-Decemb€r, Taughtthe courseCSCI 383, ProgrammingLanguagesat Hope College
1996
using the newly draftedObjeccOrientedAda 95 chapter
May,1997
Preparematerialsfor final report
List of delivorablee
l. A Cthical Ewhntian 6thc Fnlw.ww
dsron
0{/@95 by.Ao&owVor Pr,roisasdlvt nuelCal-
2. Sylahrsfsr CSCI495,Objo'&&mChgcaceirg
3. ProposEd
Cluptcrot Prcgto,,erhtglryeqrca:8@s
Object-Orientod
Modclb Ada95.
MM@&!,s, ThiddEdittq,Ttrc
4. Sy[rbu8for CSCI383,Progrsrosiaghiguagos
5. Ch4t€r cndinefor proposcd
Thidftl,fuion{f Pn&/fi,efid,qLrywAec: Sfrucno€tondModels
A CriticalEvaluationof the
of Ada 95
Enhancements
by
AndrewPieterVan Pernis
ManuelCalder6n
HopeCollegeComputerScience
SummerResearch1995
Prof. Herb Dershem
Table of Contents
Tasking
Types
Protected
Type- Entries
Protected
Requeue
Statement
TaskScheduling
Transferof Control
Asynchronous
PredefinedLibrary- I/O
TaskingExample
Generics
Generics-Unconstrained
FormalGenericPackageParameters
AbstractDataTypesand Subprograms
AliasedTypes
GenericsExamPle
Strings
SffingsExample
Object-Oriented Programming
TaggedTypes
ClassWide Programming
DynamicTYPeSelection
PublicChildren
PrivateChildren
GenericChildren
ExamPle
Object-Oriented
9
9
l0
l3
t4
t6
16
22
22
25
zo
zo
28
Manv new ieatureshave been added to Ada 95 to enhanceand expand the Ada
tasking,
of programming:
programming
language.Thesefeaturesaffect four main categories
of
All of the new featuresareimprovements
genirics.stri"ngminilulation,and object-oriented.
not all of thefeaturesareexactlywhat
Ada, butsomearemoreusefulthenothers. Furthermore,
new featuresof Ada 95,
theyappearto be upon a cursoryexamination.We will examinethese
commiirtontheirulefulness,andlist any difficultiesin usingthesenew features.Wewill also
and objectexaminehow thesenew featuresapply to tasking,generics,string manipulation
orientedprogramming.
TASKING
to
differentprocesses
Taskingis oneof the morc usefulfeaturesof Ada 83. It permitted
run concurrenaly.
Ada 95 includesseveralnew featuresthatmaketaskingnroreuseful. These
belowfollowedby anexamplethalusesmostofthem'
ncwfeatures
areexplained
Thefeatures:
I . ProtectedTypes
2. ProtectedTypes- Entries
3. R€oueue
Statement
4. TaskSchedulins
Transferof Control
5. Asvnchronous
Library- l/O
6. Prddefined
Protected
Tvpee
-- typefeature.A protected
ln oraerto slmplifytasking,Ada 95 hasincludedthe protected
betweentasksor allow
typeis a typethatcontainsiprivati part,whichis usedto passinformation
subprogramsAttachedto
on the Protectedtype's
siveralmiks to shareinformation.depending
the privatedata. Sincethese
ihat accessand manipulate
type are subprograms
the protected
aie executedin a-mutuallyexclusivemanner.theintegriiyof thedatastoredin the
subprograms
to
theneedfor additionaltasks
helpto eliminate
proiectdd
typeis insured.Thus, protectedtypes
iontrol thepassingof informationbetweenvarioustasks.
variablecansimply be
typecan be definedin two ways. Firsta Protected
A piotecte-d
created.
protected Flagi6
procedure Get(Value:ltem);
procedur€ Put(Value:Item);
private
Data:[tem;
end Flag;
protected body Flagi s
-_ Procedureandfunction bodiesfor the variableFlag
end Flag;
Second,an actualtypecanbe definedasprotected,andthenvariablesof that typecan be declared.
protected tyPe Flag-TYPei s
-- As in the aboueexonrple
Flag:Flag,Type;
through the dol notationfound
of the protectedtype are then accessed
The subprograms
throughoutAda.
Flas.Get1X);
Flag.Put(Y):
It is importanlto note that since functionsin Ada haveread-onlyaccessto the ProtectedtyPe. any
numbei of tasks may executefunclions on a protectedtype at the sanle tinle Since procedures
tyPe.only one task may executea
havetheabilitvlo ciranlethe valuesstoredin the protected
IyPe
may accessthe Prolected
no
functions
given
time,
and
prot".t.J
ut
any
procedure
type
on u'
prccedur€
executes
while
_- that
tvpesare arrincredibiyusefullbaturewhenusingtasks Not only canprotected
Protected
andflags. buttheycanalsobe usedlo prevcntracecondilions
tuo", Uaur"a ro .i"ure scmaphores
sincethe actualvalueof lhe protectedtype remains
Furthermo;e'
,iriaotu rfrui"a U"t*"eD tasks.
subprograms.the abstractionof a semaPhore
the
defined
through
privateanacan onty tte accessed
or flag is maintained.
Protected Tvpes . EntTies
--Entnesare proceduresor functionsbelongingto pro(ectedtyPesthat have a ce(aln
when an entryis called,theconditionis evaluated.lfthecondltionis
calledthe'barrier.
condition.
U"ay execures.lf ir is false.the entry call is queueduntil its conditionbecomes
i-f,."
-.w-h;;
i5i""i*
"";; Jniry is qu.u.d. the task that called ii halts Thereforeentry calls to the same
il;,
to have any impact'
Drotected
' -'-'l; element m\ist be'made from different casks
: when thiscntryi5 called the
called
thc
entry
is
"win-or-lose
example,
iit;};G;i"s
u^ri"ut"-;oointt .u.ibe eqlal to "limii or "limit" for the body to beginexecutio At the
at th€
ih" program,this will not be true. Task one callsthe entry "win-or-lose"
u"n*"re'"f-ii;;;Jf";
'6xrisr"
will
of othertasks,t5"
i,t*ili b. queu.d. Duringtheexecution
;Ei;;i;?
'win
gets
pla)ingthisgame
eiecute.WhenthePerson
or lose"willeventually
*3..eiiu"""a
points,
a
loss
is
reported.
a win or
"limif' or "-linit"
Theexample:
package for-game i s
protected tYPe gamei s
entry wln_or-losel
a gra"t
end"tfor_game;
package bodYforiame is
protected bodygameis
4
tin-o.-los"lt,hen ((points= limit) or (points= -limit)) is
",rt"y
- will getexecuted
if thebanieris broken
-- it will displaya message
on points.
depending
begin
= limit ahen
i f points
-put-line{"
YOU WON !!!! ',:
ek€
puuine(" YOU LOST???");
end if;
end win_or-lose:
end game;
end for3ame;
Exampleofa call:
task one:
task body onei6
begin
mySame.win-orJose; - thiscall will b€queued,untilthebarrier
-- becomes
true.
end one;
Reoucue Staten€nt
-W[en
reset",e[try "resct"is placed
for example"requeu€
is ex€cuted,
a r€gteuestatemcnt
in theentryqueuc.
entry signalwhen tru€is
begin
i.qo"o"
,."e1
- banieris alwaystrue
-- WHERE THE REQUEUESTATEMENT IS USED.
end sig;l;
code"reset"will be placedin the entryqueue. When €nlry "signal"
In the preceding
taiting in the queuewill be executed.
finishesexecuiing,thenall executableenlries
- Following
of
requeueis
example
these."reset"wiliexeruteif its banierconditionis true. A morecomplele
givenlater.
Task
---TA Schedulins
95.xpandsfte capabilityof rasksby allowingtasksciedulinS,Sivingcertaintask are
or otherresource.
givenpriorityover othertasks-.Thui, whentasksentera queuefor a processor
priorities.
given
prcfereoce
overthosewith lower
askswitb a Lisherpriorityare
Task icheduling'is added io any tasking p.ogram with a single statementin the
soecificationof eachtasktask Examplei s
-Entries for taskexample
pragma niority lVatue;;
end Exarnple;
5
The pragmapriority statementassignsthe taska priority bet\r'een0 and 30. with 30 as the highest
the taskwith the highest
prioiityiand0 the lowest. When tasksare competingfora resource.
tasks
with
the
samepriorityarewaitiug
lf
several
will
gain
of
the
resource
first.
control
i'rioriti
theywill be handledusinga FIFOqueue.
for lhe resource
Task scheduling,once underslood,is easyto implenrentand allows for greatercontrol over
the order of execution of tasks. Furthermore,including task schedulingin Ada 95 does not
invalidateanyAda 83 code, sincetasksdefaultto the originalFlFO queuemethodof schedulingif
they are not assignedpriorities. A further extensionof task schedulingis interruprpriorities'
as i an abort
controlof resources,
which can be usid when tasks needto immediatelygain
Asvnchronous Transfer of Control
The statement
-- asynchronous
tmosf€rof control,
s€lect
delay2.0;
thenabort
end seleci:
tolt supposed
saysit isnotyetimplement€d.
seemsto
"not"le working. CNAT docudentation
lf
are
executed
first
"end
select"
and
the
"then
abort"
the
between
wori so thatthestatcmei'ts
thevtakelonsertoexecutethanthetimespecifiedafrcrthe"delay"'executionisiterrupte
insiead,theitatementsbetwe€nthe "deiay"and the "thenabor("are execuled.When the
takelesstime thanspecifiedin thedelay,CNAT worksfine But, whenexecutionis
statements
fault"is rePorted.
a "segmentation
timeelapsed,
because
intenupted
PredefinedLibrarv - I/O
-==--ir
from thatof Ada S3 Several
T--O-libr"ryof Ada95 remainsvirtuallyunchanged
as
Flush, Look-Ahead'and
such
to
it
however,
have been added
usefulnew feat-ures
writren
under
Ada83, no Previously
programs
to
support
in order
C"i imiaiui". Furthermore,
fashion'
any
significant
changed
in
funcrionswereremovedor
exist-ine
flushesa bufferto a lile, or to the currentoulpul
Flush immediately
ihe procedure
whenworking
is alsoimPortant
TheFlushprocedure
*hirtrerafile tas specified.
aependinsoi
will
thenbesent
buffer
that
to
a
will
rasks
ourput
*iit t"ii!. sinc".ost implemenuiions haverhe
difficult'
debugging
making
not
before,
and
outpu,nle when thetaskis completed.
to ttr"
sentto
to
be
immediatrely
a
task
ptustr"urr"ni
process
output
of
by foacingthe
simotifiesrhedebugging
is a
Lrok-Ahead
executing.
taik
finishes
if,"."J"iiii" i"rt""a.f re"riaiiihgin the5uffe.unlil the
without
input
a
file
and
of
cha.acter
the next
the userio determine
,."""airii-if,"i
a file or thecurrent
"iio"s
procedure
readsthenexl characterfrcm
Cer-lmmediate
ioniu.i"e ii. The
ger
rhesranda.d
page
like
terminarors
or
any
line
anddoesnotskip
ii
i"""iiiii ir
abiliry
and
the
"i"ilable,
"".
as
subpack-ages'
a;d
Decimial-lo
citi'r"iaooiiionsin"ruaeModular-io
il;;;;;".
i;;ih;i";"i;;
the
errorfiles ln-general
andCurrent-Enorfor
s;LEiiot. Srana"ra-En6r.
betwe€nAda 83 and Ada 95 only a lew' nelplul
predefined
libraryText-lo remainsunchanged
featureshavebeenaddedto it
An Exarpple of Taskine
----E
was takenfrom the Ada 95 rationaleand was modified a little so
foll"*rne
of the Ada 95 featuresof tasking
lhar incorpomtesmoat"')(ample
PscLrs! f(rf_evtnt I s
protect€d tJtPeevcnt i.
€olrJ tr4il;
lntrJ €i8[st:
Pilvat
€ntry rc9!{;
oconEd: b@leonFfdrq
anil fot_cvcht:
prckrg. bod/ forrevtntI r
proa.ct d body evanll.
antry wsit stan eqrrldlr
b.gln
puuildirylit i6(,(€cued'):
?lurh:
a||d wair:
- b{riar trdn4}a fiuc
.ntrJ ligtul rh.n treoI r
b.gln
puLlin{' Signaltu lr.cfltcd ')i
flrrih;
lf writbount> Othan
oq*rtd := t!e;
- b nrb flt$.&p ttfitrFtI9 bd.rE &qlFue,
d.l.y( l3):
.. wERg'tr'HEtFQ[rtsrs
ls usED.
srATgrrrB!,lr
tlq|tauc rctct;
rnd lq
.!rd rig|aE
Grtry rcapttrh.n waitbountE 0 I t
beghr
putJiE(n R.€etis e,(ccurrd.');
flu.h;
@trF4= fsls.:
and ft€et;
cnd ev€nt;
crd foLevenq
plocadut! lraitrl l3
m,_ev€nc evonq
lqk tyDe orlc;
trsk body one i 3
prrgm! Priority (3o);
begla
7
p u t _ l r n c{ " F i . s t $ t l i t " ) :
flushi
pur,linc (" SccondNnil "):
flush;
lrsk body lirr) i s
pragme Prrcril)._
(29):
begin
delay(l.())r
put_linc("FirsrsiSnalr')i
flush;
nu_e!cnLsrgna{1
delay(1.0)i
plt-line(" SemndSignal"):
llushi
nl)_e!enl.signal;
\rllm!(1..3) ol onc;
b€gln
nulli
€nd matnl;
Hercis whathappenswhenthe pre.edingprogramcxccutes:
First, the3 "first waits"arequeued(3, b€caus€
thereare3 tasksof type "one"). Thenthe "first
signal"getscalled,this rcqueuesireset'. Thus, "resct"is queu€db€hindthe 3 "waits".The 3
arldthe "reset"follows. Thenthesamething happens
againwith the
"waits"arcnow executed,
"secondwaits"and"secondsignals".
The taskingfeaturesusedin this exampleare:
Protectedtypcsi
lype.
Typ€"Event"is a protected
Protectedtypes- Eotriesi
"Wait","Signal",and"reset"ateeDtries,
RequeueStatement;
"r€iueuereset"is in entry"signal".
TaskScheduling:
Task type"onenhasa higherpriority thantask 'two" thereforethe tasksof the arraywill start
ro ensuretbattfe 3 i'first wails"are queuedbeforethe "sigml" in lasktwo is called'
execution
This enablesthe useof the requeuestatement.
PredefinedLibmry - I/O
"flush" is from thelibraryI/O. Without"flush" we maybe gettingth€ outputatan incoraect
time
andwe won't reallyknow whatis happening.Whathappens
withoutthe "flush"is thattheoutput
goesinto a buffer. This bufferis outputted
to thescreenonly whenthetaskfinishesexecution
or
when someother thingshappen. To be surewe get the outputin the correctorder,we use
"flush". This ensuresthatthe outputis displayedon the screenwheDthe "put" statement
is
reached.
GENERICS
With generics,
we cansavewritinga lotofcode. Genericsallowus to writepackages
and
procedur€sfor an undetermined
type (the gen€ric parametertype) and instantiatethe
package/procedure
for anytyp€we need. For example,supposewe needa swapfunctionfor
integers,onefor reals,andonefor characters.
Insteadof writingthesamefunction3 times,each
timeonly changingthetypesin the paramcters,
we write a genedcfunction,andinstantiatc
it for
integers,rcals,andcharactcrs.We couldalsoinstantiateforstringsand arrays,as you will sec
later. Ada95 givesus newfeaturesthatallowus to enhance
Ada'sgenericcapabilities,
including
genericpackageswith
unconstrained
types(strings,arrays,etc.). Wewill first explaineachnew
feaeuae,
thenwe will givea complete
examplethatimplements
a genericstack,usingthesegeneric
Ieatures.
Thefeatures:
l. Generics- Unconstrainedparameters.
2. FormalGenericPackasc
- Parameters.
3. OtherImprovements;
4. AbstractTyp€sand Subprograms.
5. AliasedTypes.
GGn€rics. Unconstrlined
In Ada83, g€nericpackages
did not acceptunconstrained
typosasparameters.
Thatis, we
couldn'tinstantiat€
a pactagcwith thetype "string"or somesort of arraytype. This limitedus
somewhat. Now, with this new featur€,Ada 95 pcrmitsthe use of utcoNtrainedtypesas
parameErsto a genenc.
This featuredoes,however,havea necessary
limitation.Wearetrot allowedtodeclarean
uninitializedobjectof type T (the unconstraioedparametertype)in the body of the generic. Thc
following code will illustlte this limitation. Supposewe watrt to createa genericswapfunction
for unconstrained
typeard lct type "T" be the generictype:
procedure
Swap(A,B:T) is
- <--- This is not valid.
Temp:T;
begin
Temo:=A:
A :=-B:
B := Temo:
end Swap;
But when we write "Temp:T" we are declaringan(uninitialized)objectof a genericunconstrained
type, which we are not allowedto do. Thereare ways aroundthiS. We could still createtheswap
functionusingpointers,butthisis a complexprccess.
1'heway to makea generic-unconstEined
packageis:
generic
type T(<>) is privatet
package gen_stacki s
end ge;-;tack;
Functionsor proceduresthat usethe unconstrained
type are written as follows:
procedure push(a:in T) is
b eg i n
'fo
"na
puiit,
thepackage
for th€type"string"we write:
instantiate
is new gen-stack(string);
packagestring_gen_stack
will be
I \,r'illgivea complete
example
in whichge encs- unconstrained
At theendoI thissection
further.
usedandexDlained
l-ormal Generic PackaeeParameters
in Ada95 with theadditionof formalgeneric
expanded
Theconceptof genericpackagesis
allow the user to definea generic
packageparameters.Formal genericpackageparamete.s
which
generic
package,
is accepted
asa iormalparameter
package
compiled
basedon a previously
'Thus
numbersthat
generic
paikage
created
for
complex
package.
a
iould be
bf the-ne*g"ne.ic
-of
generic
package
thathandles
another
Then
acceptsone the viriouJfloartypesfor instantiation.
of the
polaroperations
would
accept
any
instantiation
on complexnumberscouldbe createdand
parameter
packages
uPonits instantiatton
asa
numbers
originaicomplex
paikageparameters
into a programis fairly sirnple. lf. as
formil gen-e.ic
lncorporating
andtheother
whereonehandledcomplexnumbers
above,we wire creaiingtwo genericpackages,
couldbedefinedas
on complexnumbers,
thesepackages
handledpolaroperations
ge||eric
floaf_lypers orglt6:
is
packageGeneric-Complex-Numbers
type Complexis private:
function "+" (Left, Right:Compl€x)return Complex:
--(Similarly
for -,/,ft,etc.)
end Generic,Complex-Numbers;
and
with Generic-Complex-Numbers;
genetic
(o);
is n€w Generic-Complex-Numbers
with packageComplex-Numbers
i
s
packageCeneric-Complex-Polar
t0
-- Types,functions,andproc€duresnecessaryfor polar operationson complexnumber
end GenericComplex_Polar;
Instantiationof thesetwo packagesis thenaccomplishedby thefollowing statements.
package Complex_Floatsis new Generic_Complex_Numbers(Float);
p.ckagc Polar_Complex_Floats
is new Generic_Complex_pola(Complex_F1oas):
. Thereare severalproblemswith this featureof Ada 95, First, if an originalgeoeric
packageus€san unconstrained
parametersuchas
generic
Float_Type
is digits +:
then.a.subtypeor derivedtype of the ulconstrained
pammeter
must be declared
if that typ€ is
neededwithin a secondpackagethar uses the original packageas a formal genericpic'kage
pammeier.Second.givenan instantiationofa genericpackage,no morethanolnene* g.n.ic
packagemay be instantiated
within a singleprogrgmusingthaioriginalinstanriated
packa-ge
as a
formalgenericpackage
parameter.Forexampleif therewir€ three-generic
packagejforco;otex
numbers,GcNumbers.CCPolar,and GCVectors,where both Gtpola; and 6cvecrors had
GCNumbersas a formalgenericpackageparameter,
thenthefollowinginstantiation
of the thrce
packages
wouldbe invalid.
packageComplex_Floats
iE n€w GcNumb€rs(Float)i
packsg€ Polar_Complex_Floats
is new GCPola(Complex_Floats);
pockage Vector_Complex_Floats
is new Gcvectors(Cbmpl€x_Floats);
This severelyrestrictstheuscfulness
of formalgenericpackageDarameters.
As far as couldbe
d€tcrmincd
from theexistingdocumentation
for Ada 95; this ls i restrictionimDosed
by Ada 95
andnorspecificto anyimplementarion.
are still quite usefulfor
. Despit€theselimitations,formal genericpackageparameters
creatinggenericsystemswithinAda 95. This featureis just unableto reachits full potentialwith
thc.prcsentsystem,but it still does gr€atlyexpandthe usabilityand usefulnessof generic
pacKages.
Abstract Data Tvpes and Subproerams
An Absract DataType is a type that servesas parentto othertypes. It can havedats
elements.thatall its childreninherit,andabstractprocedures
and functionsthat, althoughthey
don't do anything,requireall childrcn to havethere subprogramsasw€ll.
For examole:
Supposeyou have3 differenttypesof tires. The 3 tires havccommonfcatures,but no tire
has featuresthat area supersetof the featuresof atrothertire. Thus, no tire inherits qualities
from another. There is no reasonthat one of thesetires should be the Darentof anv of the
others. [n thi scase,.an abstraclbase_tire_type
could cootaiothe commonq-ualities
of ali 3 tires,
andthenhaveeachtire tvDeinheritfrom bas€ tire tvDe.
An advaDtage
is thatthis leiithe programmerimitateilid real world in a betterway.
An example:
Considera phonedirectorywhereinformationfor "Basic',and for *Complete,'
can be
stored. By .Basic,"I meanrelativesand
all acquaintances.
By "Complete',
I meanilose friends.
SinceI am mostlyinterested
in "Complete,"I wantmoreinformation
bn them, Thus,the entries
1l
for "Complete"
will allowmeIo entermoreinformation.
,,BaseDirecrory
Thebase-rype
is "BasicEnrry,'which
is in packagecalled
Enrry,'.
l.his
,
.
Jbstract
typehasa dataerementcalled
"Name".Thisrequiresalldirectoryentriestohaveaname,
(regardless.of
"Basic"or "Complete").It alsohas an abstract
proiedurecalled',Display,,,
requiringall directoryentriesto havea wayof displayingthemselves.'
" inheritsfrom ',Basic_Ently,i
andaddsa dataelementcalled',Telephone,,.
]Ngnnal_Entry
,.
,'Basic_Entry"
It also Includesthe proced^{c''Display''.
Remcmbcr,
is rhe abstracttype and has
ihe.abstrachubprogram
."Display". This meansthaiall types inherilingfrom it, wi[ 6jve to have
tnelr owll ulsptay-, s cn ls the caseheR,
"Compiete-Entry"
inherirsfrom "Normal_Entryand adds the data elementsAddress,
,
(^ ommentl.and Comment2.lt alsooverwrites' Normal
_Entry,',sDisplay".
The codefor thesetypesfoliows:
packagebase_directory_entry
is
type basic_entry
is abstrsct tagged
record
name:string(1,.100);
end record;
procedure display(bei
in out basic_entry)
is abstract;
end base_directory_entry;
prckage normal_directory_entry
ig
packsge int_iois n€w integelio(integer);
use lnt_to;
type normal_entry
is new base_directory_entry.basic_entry
with
record
telephone
i string(
1..100);
end record;
proceduredisplay{ne:
in out normaL_entry):
new normal_entry
with
procedure display(ce:
in out complete_entry);
end normal_directory_entry;
I2
package body normal_directory_entry
is
proceduredispla)(ne:
ih out normal_enlD
) is
Degrn
pu(" Name : "); pu{ine(ne.name);
: '): pur_
line(ne,telepnoner;
Put("Telephone
end display;
procedure display(ce:in out complete_entry)
is
begin
display(nomlal_entry(ce))i
put(" Address : '): put-line(ce.address);
Pu(" CornmentI: "l: put_line{
ce.comment
I );
PUT{" Comntent2: ')i put_line(ce.comment2):
end display;
€nd normal_dircctory_entry;
Aliased Tvpes
Pointershave been_
grearlyenhanced
in Ada 95 throughthe use of aliasedtypes.
^
l)rcviouslyit wasnot possibleto createpointersto objectsdeclaredisvariables
or consrants.'Ihe
addrtronot aliasedtypesro Ada95 allowsa pointertopointto anobject,insteadofneedingto be
dynamically
createdasbefore.Aliasedtypesareusedin thefollowin! manner
type Float*Ptris accessall Float;
typ€ Const_Ptris access conctantFloat;
Pointerl:Float_Ptr;
Pointer2:Const_Ptri
A: sliased Float;
G: aliased constant Float:= 9.8;
Pointerl:= AAccessl
Pointerz:= GAccesst
ln thedefinitionof an accesstype.the all qualifierindicates
pointerswhich will point to aliased
variablesandthushavereadandwrite access,whereasthecilnstantqualifierindicates
thosethat
will onlyhavereadaccess
to thevariableto whichtheypoint.
A liasedtypesnow allow for easymanipulation
of pointers,withouttheworriesof dangling
^
relerences.Furtbermore,
aliasedlypesallowpointersto point to constantvalues,restrictingsuch
pointersto.readonly. evenwhen theypoint to a variable. Furthermore,
constantpointe;sand
variablcpointerscannotbeinterchanged,
but constantpointersneednot point to a constant.For
example
Pointer2:= G'Access
Point€rz:- A'Access
--a pointer to a constant
--a pointer to a variable
sincePointer2isof Const_Plr
lype. Pointer2
wouldhavereadaccess
only to G or A with the
aboveassrgnment
statements.
eventhoughA is a variable.Conversely.
a variable
pointercould
l3
nol be assigned10poinl to a constant.
A l r h o r r g h r h<
e i)r c , n o\ et r ) u s e f u tl o r c r e a t i nlga r g cl i n k e dl . 5 l s o r o r h e r p o i n t e r 5 l r u c l u r e r ,
-,
* q e ,r i s e dr o f c r e a r r n B s m a l l . l i nskter d
u c r u r e \t.h e p r o b l e n r w i r h ( r c a r i n g t a r g e
L
, . ' l * ist.rctures
. l y _: :f . "wlth
r.nKeo
alr"sedtypesis that eachnode needsto be declaredas a variable. whiie th]s
e t r ' ' , r n a t e spt hr oe b l € m
ol danglingreferences,itisnotveryefficient,norisitasdynamicasatrue
rnKeosrrucrure.
ul course.
a llnkedstructure
usingaliased
typeswouidbeeasyto rearrange
and
manrpLrlale
as ncce-ssary.
sincerhcpoinrerscan bc directlyassigncd
to pointto t'hevarious;dcs,
wrtnor|ttneneedot a temporary
poinrerto hold on to a disconnected
node.which would become
a
danglrngfelerence
i. a normallinkedstruct.re. Furthernrore,
aliasedtypescan be usedto poinr
i'rto the middleof contposite
rypes. Thus, it is not necessary
to creatii pointerto a recoid,to
i c c e s s\ o m e t r e t do ' t h a tr e c o r d h
. u t r a t h e tr h e n o i n t ecf a nh c a s s i p n eldo p o i n td i r e c t l )( o r h e
desiredfield.as Inngas thaI field is markedasaliased.
An Dxarnple of Generics
"l hefollowingexampleimplements
a stackof
any{hing.
Thatis, thestatenrent
package int_slackis nei" stack(integer);
instantia{es
a stackof inlegers-The samecan be acconplished
with stringsor any othertype,
constrainedor u constrained.
l hesameproblemoccurshereas in the "swap"function. Tohavea linkedlistweneedto
declarca rccordin which one of the elements
is of typeT (the genericunconstrained
type). As
you knowby now,we cannotdo that. Thewayaroundthisistousepointersorastheyiricalled
inAda"acccssvariables".'l'hatis,intherecord,insteadofhaviDganelementoftypeT,wehave
a pointerto it (an accessvariableto type T). Therefore,the recordcontainsone elementthat is a
pointerto T. and ano(herthat is a pointer to the next element(since the stack is implementedas a
linkedlisr).
It turns out that the "genericunconstrained"featurecan be usedto createmany different
..
kindsof datastructures,
suchas stacks,binarysearchtrees,hashtablesandso on. Thisis very
useful,because,
for example.AVL treesarenot trivialto rewriteeachtime we needthemfor i
differenttype. This way, we just instantiate
our genericAVL treefor rherypewe needand rhatis
l'he codefor the senericstackis as followsi
-'This rmpleolenLs
a slackof unconstrlined
rlp€ T.
- Ir hrs pR,ccdLrrc
push.rndlunclronF()p.
- Pushrukcs an clcmcnlol qpc T.
- pop:rc(urnsan clemcnlol-typcT,
with ad.r.rc\l_io.ada.slings.unbound€d,
ad&inlcger_(exl_io,ada.lloal lc]iL,ioi
use ada.re\r_ro,ada-strings.unboundsl,
adainleger_tcxr_io,a(Llll@t_tc\t_rci
generrc
tJ p€ T(c) is privater
packag€8en_st.rck
is
typo T access
rsprivate;
type lrst n.xlcl
l4
typ€ linked_lisl is rcc66 lisl-nodc;
type lisl-n(xlei5
pdara: T3occss;
next : linked-lisl;
- this will bc poinling &' th€ dataT
i i integer;
ll: linkcd_li.t;
- ller€ lhe *l{ck will bc.
P.occdurcFrsh(a:ln T);
funcllon F p fttum T:
prlvrte
type Tiacltsstr r.c..r .lt Ti
- poinr.r h d|e gcnerict$e T
end gen-rcack;
p.ckrg. body 8pn-6Ek l3
stacllenoc exceptioo;
procadorrFrh(a:In T) I5
tcmp: linko(Uist;
b.gln
trmp ;= ncw lbi-nodclrcw T'(a),ll);
ll := !?rnp:
.nd pu8h;
?onctlonpoprrtlm T l,
- if it ie null, rhclriawill rcrurnnull
@mp:linkedjist;
b.8ln
la U=nuuth.n
- Ilis€ anexcepiion
nlra €tack-error;
al3€
t€mp:: lli
ll:= ll.next;
I li
rtturn remp.pdala.r
cnd lt
etrdPoP;
cnd geLslacki
The followiag showshow to iqstantiatea stackatrduseit.
procedBrc
maini6
packege sningjen-stack is new gen-stack(sttitrg):
u6e stringjen_stack;
push("Hello ");
push(' Matruel');
l)
pu(pop);
Put{pop,:
end mair;
The progranrwould outPut:
ManuelHello
Strinss
-----Freviously,
Ada did not supportstringsto a largeexlent Alrhou,ghthc stringlyPewas
Jefinedfor lhe slrirlgtlPc
defined,it only ailo$edslringsof fixedlength.andlheonly oPerations
librarieq
toAda95isthc
Thus.I majorexpansion
undconrpiarison
PredefrneJ
u
and
unbounded
boLrnded,
"t"
"on.ui"ni,io',
fixed
length
covering
for strings. Thereare severalnew Packages
s t r i n g s , a i r n c l l a s c h a r a . t c r m : p p i n g 6 e t w e e n sFt ri ixnegdsl e n g t h s t r i n S s a r c i l r i n g j $ h i c h h a r e
a sctiensthand muslbcpcddcdillhc dcsircdslringisnol longcnoughtofillthcstritrg Boundcd
(rnb'rLulde'l
l e n s t h s ; i n e hs a v e am a i i m u n r l e n g (bhu l d o n o t n e c e s s a r i l 5 h a v e t o f i l l l h a l l c r r g l h
striies
- '_' aresiringswhichcarrbeof any length.
tnlrnuni* functionsaredefinedu-ithineachof thesepaclagesfor the differentttles ol
strinss. So;1eof the mostimponanlf'nctionsarethosewhich allow the userto convertbetween
strings,such-as
rhe tlhreestring types. The majorityof the functionsare for manipulating
of a
occttrrettces
the
numberof
countin€
or
r;t
of
{he
string
ii".:!i.""tliii, i"iii lng rhe head;r
are
there
t)
the
slring
well
ior
maniPulaling
as
functions
l'es
*irttin a stri;g. As
i"6ii-n
new-predefined
these
All
of
sirings
unbounded
i""",i.". definedfor boundedand
""roari3ro Ada95. by rnakingit simplerand moreeffrcienrfor the user
rii,raivpi"il"gi, iaa significar)rly
with strings.
to
.' work
-"in.ii"a-oii"tailing
d€finedin lhe new predefined
all of thc functionsand proccdures
will be
in
the exampleprog-raft
procedur'es
used
functionsor
fiu.uruoa"t"e"t. only th"ose
4
ot
the
AdavJ
aPPendlx
A
refer
to
more
information
examin;dafteithe actualprogram For
Manual.
Reference
An Exapple Prosram for Strinss
-Tf,;Drdffil;lh-is
lengthand
stringsof up to 256charactersin
example&ceptsmessage
by
theuser
is
entered
messages
program
to
tnnllate
thl
oi,i".o'a".. The codeusid by
"n"oa"r
mappingfunction
andis sloredasa character
with Texl-lOluseTc\l-lOi
uE€AdaClura.te$HardlinS;
11lth Ad&Charactcm.Handlingi
use Adi!SltingsUoboundcd;
with Ada-Shngs.Utlb()undcd;
with Ada"sringsBoundsli uEe Ada.Strin8r.Boundsli
Fixcdluse AdaSlrlnssFixcdi
wlth Ada-Strings
use Ada Slnn8s.MaPsi
wtih Ada.Strings.Mapsi
procedur€CodeMaleri s
us€ Codestrinssi
packageCodeshn8si s new Cenenc-Bounded-tinglh(26);
is
protected aYPeMessages
n8i
U
ntounded-Stn
retLrrn
Rcad
function
Unhrundal-Srnng)i
procedureAdd (NewMessaSei
procedureclcar
lb
priv.tc
ThcMe$sa8qUnburxkl-String := Null-Unbound€d-String;
end Mc.\Tage6;
prot€cred bodl' M€ssag6 l€
tutrclloo Rcadrctum UDboundo$tring i s
begtn
rcturn TheMe$age:
€trd Red;
proccdurr Add (NewL{e$agq Unbound€d-Strin8)i s
b.gln
TheMesfalF:= TheM€s&{e & NeNMessagei
€nd Ad;
proccdurc clcsr t .
b€gln
TheM6sags i: Null-Unboudled-String;
end Clerr;
end McasalFs;
MflSdmt€souct CodcdMessafc,Drcododtvr!€satc:
Messrges:
t.sk ErFoderi t
.nt"y lncotning(lvl.6erge:Unbouded-S8ing);
entry Cod€Defn(Origi@l,Cod€:
Bound6d_SEing);
€ntrJ Quit;
prtgrhr Priodty(t;
cnd Enco&i;
trrL body E$oder I s
typ. lvlapRr l3 .cc.3i rll Ctutecler-!,,1+ping;
CodcRc MapRr;
Map: rurrcd Chamcl€r-llapping;
Finish€d:Bmle€n := &he;
bcaln
Ioop
selact
acc€pt lncoming(McqeaSd
Unbound.d-Srin9 do
putJin(i<<<Encodinp>>r),
daclara
.
Copy: Striogr=TojtrinSod€8lage) i
begln
CoPY:=To-Low€(CoP!')'
Txanshqcopy,CodoPk &ll);
Codcdlaca6iSaAdd(Io_Utrboundasf ing(Copy));
Wi[sclfDdtrucl"Oear;
DecodedMassaSe.Ct€ar;
end;
puLtine.("<<<Complet >>>'X
cnd Incoming;
accept Cod€Defn(Origiral,CodeBound€d-String)do
l7
Map:= To-lvlapprng(ToJlrin8(O.igioal)'To_sEanS(G'Je)):
C(xlcPk := lvl.rp'Acccss:
rl
erd C(xjcDcl
acc€ptQuitdo
Finished:=Truel
endQuit;
delsy(l.O)i
exit *hen Finishcdi
cnd Enc\xler:
tssk De(deri s
Un&}urdcrj-SUing);
entry lnc{)lning(Mcsrugc:
Boundsl-Shng)i
entrJ C(xleDcln(Odginal,C(rlei
.ntrJ Quit;
pragma ftiorit)(3)r
€nd Deqrderi
l!6k body Dsjdleri s
LlpeMapPLri s acce66all Clunctcr-MaPPinS:
CodcPlrrMsPPl.i
Map:alhsed Chrl*-lcLNhPPln8:
FinishediBmlcan:= Falsei
bcgln
looP
rcc.Pt lnooming(Messgq Unbundcd-SrinB) do
nP>>") i
pul-line("<<<Decodl
d.clere
To-StrinS(Mcssagc)i
CopyiSLrinSr=
b.gln
To-t-o\\'e(CoPY);
CoPYr=
Tr.rnslate(CoPY,Co'dePtrall)l
Dc.dt€dMcssnge.Add(To-Unboundcd-SlrinS(CoP!));
WillSellDestruct,Clear;
CqledMessagcClear;
end;
i
);
Pul-linc( <<<ComPlcrc>>>"
end lncornlnSi
scccPt CodeDefn(Original'Gie Bound€d-Slring)do
Map := To-Mappiog(Io-slring(Cod€)Joj'rin8(Original));
codcPtr := MaP'Access:
end CodeDefn:
acc€PtQuitdo
Finished:=True;
end Quil;
l8
dehy( I.o):
€nd selec(;
exit rvhen Finish€d;
t$k
Crea&Code l f
entry Newc( e;
entrJ Quir:
pr.gm. ftiority(7);
e.d cftdccodc;
t.3k body crq.lrecodc
Is
Finishcd:B(blean:= Falsel
b.gld
l o op
r.ccpt Newcodedo
daclara
Original Bound€d_Sting:= Null_Bouded_String;
Cods Boudcd-Slridg := Null_BoundEdJtring:
Origincharcodechar: Clhadcr.r;
b.gin
pu(.linc('rEn@r
a r.rio exir,);
loop
pu('Ent€r thechriacter of thc originul rcxu ');
gc(Originchar):
skip_tirc;
I t O.iginchar= '.' th.r
axlt;
ala!
I f (Codcsrdngscodn{O.itir|.l,To_Sc(Oidnchar))X})
rh.r
pullitF('That cl8mcter har atEddybocser ced.");
clslf no(h_Lrtrr(Odgnchnr)) th.n
puLline{"Tht cfrstlcter is nol valid.");
€l6G
Od8inchar:= To_Loipe(OriFncha.);
Apped(O{ignrl,Originchrf);
looP
pu("Eobr|hecha&cferof drcoodcdtaxt "):
gp(Codeo|sr):
skip_tin€;
| | (Codestridgs.Coun(Codc,To_Set(Cod€Ctar)>O)
th.r
Ftuinq"Thst chalsctcrha6alft2dyb€en€nt r€d.");
clt€
Appctrd(Codqcod€Char);
cxlt:
cnd if;
€nd loop;
end I f;
€nd lt
€ xlt whcn trngth(Original) = 26:
cnd loop:
t9
Encodef.C( eDefn(Onginjl,C(d€);
Dc(xjcr.C(rlcDelh(Ori8i&rl,C(xlc);
€no;
€nd Nc$'Qxlc;
rcccpt Quitdo
Finish€d:=True:
cnd Quir;
detay0.0)i
€nd sclcct;
exll when Finishedi
end crcurecoil€;
task Conlrolleri s
prsgm. Ftiority(o)i
cnd Conuollerl
task body Conldlcr I E
ChoicciChar&teri
FinishcdrB(xt€ln := Fslsei
M€$agcrSlrinS(1..:56)i
L,ength:Nlrur.rli
begln
dcley(5.0):
loop
Flush;
new_llne;
puuinc(rWouldyou like ll).i)i
puLlinc(" l). En|€ra Mcssagc");
pul_linc(" 2). Encod€a M€ssaSei)i
puLline(" 3), D€code
a lvlcssage')i
pul-line(" 4), Chsngelhc Codc");
|
put-line(" 5), Vi€vrlheouncnlen(}led messlrgc.
);
put-line(" 6). View thecunenld€oJdslncssage.");
putJinq" 7). Cler.rallmcssagcs.");
putjine(* 8). Quit");
new_Ine;
po(iEnreryourchoicc(l-8): ')i
gc(Choice)i
skip-linei
new-tlne;
case ChoiceI I
when rlr=> putJine(rrEnler
thcme€sage
belowr");
geuinc(Mcssagc,l-ength)
:
WillselfDeltnrct Add
CIo_Unbundcd_Slring(M$sage(t..L€ngrh)));
whcn'2' + Encoder,lncoming(Dccod€dM€ssage.Read
& witlselfD$truct.Read)1
codedmessage
is "):
Put-line(iThe
puLlioe{To_String(CodedMe38age,
Read))l
when 3' + Decoder.lncoming(Code.dM€ssage.Read
& willselfD€strucl.Read);
pudine("The decdled mesclgeis: ');
20
puUinc(To,Slring(Dccul€dMcssage.Reid)) ;
whcn 4r => Crcatcc(xlc.Nc\Cqle I
rrhen '5' => puL Irnc("'lhc cuffcnr cnd)dcd mcssjgeis: i):
pur,linc(To Slnng(C(xlcdMcssrgc.Rsd));
$hen '6' :> pul_linc("Thccurcnl dccodcdmcss!8cis: "):
pul_Unc(ToStnng(DccrxlcdM6e8e.Rcf,d)):
wh€n 7' => W iiiscil Dcsktlcl.Clc.r:
C(xiedMessagc.Ciea|
clq:
tuJedi\ls$f'
,En.txlcr.Ouir:
;;.il:=-:i;,",
wlcn oLlrcrs+ pur_1inc("'ihlr choicc is nor \ alid.,,)i
cnd c!rs!:
nc\._linc:
exit $hen Finishcdr
end l(x)Dl
cnd Conlrollcr:
lregin
Crcrrtcc(xic.Nc\r'Culc:
delay(1.0):
etrd CqlcMdicr:
The followingfunctionsandprocedures
wereusedin theexampleprogramandarefronr
the library packages
Ada.Characters.
Handling,Ada.Strings.Unbounded,
Ada.Strings.Bounded.
Ada.Strings.Fixed,
or Ada.Strings.Handling.
It is inrporrant
to note that many of the
subprogmms
existasbothfunctionsandprcceduresFirst, boundedlengthstringsare implemented
by usinga genericpackage,so bounded
leDgthstringswereinstantiated
to beoflength26 i|l orderto holdtheentirealphabet.
The '&' operatortakestwo stringsoi thesametype(bounded,
unbounded,
or fixed length)
andconcatenates
tllemintoonestring.
A character
mappingfunctioi canbe definedthroughtheuscof thefunctionTo_Mapping
whichacceptstwo fixed lengthstriogsandreturnsa functionwhichwill urapa char'acter'in
the
first stringto a corresponding
character
in thesecond.
Thc functionTo_Stringrvill conl'erteithcran unboundcd
or a boundedstringto a fixcd
lengthstring with a lengthmatchingthatof the originalboundedor unboundedstring. The
functionsTo*Unbounded_String
and To_Bounded*String
will convertfixed lengthstringsinto
unbounded
andboundedlengthstringsrespectively.
To-lrwer is a functionthattakesa stringandconverts
all of its characters
to lowercase.
The procedureTranslat€
takesa stringandtranslates
it usinga chanctermappingfunction
providedasoneof the parametersto the procedure.
The functionCountcountsthe numberof instances
of a specificsubstringor character
within a string.
The Booleanfunction ls_Irtter determineswhetheror not a chamcteris oneof the lettersof
the alphabet.
Appendis a procedurethat addsa characteror substringto the endof a string.
Thefunciionl-engthretumsthelengthof a string.
lt is important
to notethatgetandputprocedures
areonly definedfor fixed lengthstdngs.
Thus,in theexampleprogmm.
thesizeof themessage
is limitedto 256characters
because
it nrust
be readas a fixed lengthstring, but it is convertedto an unbounded
stringfor use within the
2l
progrant.Theproblemof only beingablero readandwrile fixedlengrhsrringscanbe solvedin a
n0mber_of
ways. The simplestmethodto orrtputerlhera boundedoi uDbou;dedstringis to use
theTo_Slri g functio|like so
put line(To_String(The_Bounded_or_Unbounded_String);
Readingstringsof indeterminare
lengthas input is a little moredifficult. The stringcould be read
characterby chamcterand eachcharactercouldbe addedonto the end of the strins;s it was read..
which worrldworl well for u0bou[dedslrings.bul \aould req rre a larqeinrounl oI error
checkingfor_unbounded
strings. Or. srringiDtur could be brokerrrrp inro irnalleriixed length
stringswhich are thenconcatenated
togetherto forrn the entirestriog. The easiest
solutioo,-of
course,is-to limitthe lengthof stringbeingenteredro a set lenerh.$hjclr \!ould by definition
makc il a ilxed lcngthstringObiect-Oriented Proeramminp
l'he are three main componentsto objecForientedprogramntrng,encapsulation,
inheritance,
and polynrorphism. Encapsulatton
was providedin Ada 8J throughthe use oI
packages.Ada 83 alsoprovidedinheritace r.vithderivedtypes. The additionof polymorphism
has madeAda95 a t.ue object-orienledlanguage.The new featuresin Ada 95 which are relatedto
afe
Polynorpnrsm
'fagged'l'ypes
I.
2. ClassWide Prografiming
3. DynamicType Selection
4. PublicChildreo
5. PrivateChildren
6, GenericChildren
Taeqed Tvpes
PolymorphismisaddedtoAda95throughtheadditionoftaggedtypes.'fheinheritanceof
is
taggedtypesallowsfor the creatioDof derivedtypessimply and efficiently.This inheritance
extended
to all typesderivedfrom theoriginaltype. This canbe seenina simpleexamplewhich
hasthe followiDghierarchy
Rectaagle
/
\
\L.1|/
Square Cuboid
v
Cube
In the above exampleCube inherits from Cuboid which inheritsfrom Rectangleeven though
Cuboid is not definedas tagged.
Taggedtypes allow for object orientedclassesto be dcfined easily. Any funclions or
procedureswhich immediatelyfollow a taggedtype definitionwill be the operationsassociated
with the class definedby the taggedtype and will be the operationsinheited by childrenof the
taggedtype. Thus,rhe hierarchyabovecouLdbe createdas follows
22
type Rectangle
i6 tegged with
record
trngth: Floar:
Width:Float;
end record;
function Size(R:in Recrangle)
return Floatis
begin
.eturn R.l-ength* R.Width;
end Size:
type Squareis new Rectangle
with null record;
type Cuboidie new Rectangle
with
record
Height:Float;
€nd record;
function Size(C:in Cuboid)return Floaris
begin
*
*
, ^. retrrn C.kngth C.Width C.Heighr:
eno )lzel
type Cubeie newCuboidwith null recordi
The first class.Rectangle,
is thebaseclassfrom whichall of thc otherclasses
inherit. It conEists
ot a record.
with two fields,Lengthand Width. Thereis alsoonefunctiondefinedfor theclass,
5rz€-,which.computes
theareaof thc rectangle.The-nextclass,Square,is an exactduplicateof
Kecrangte-.
$nceme recordts not expand€d,
no newfunctionsor procedures
aredefined,andthe
Innenteoluncuon)rze rs not redelrned.ln a morecomplexstructure,
wherea Derimeter
function
was-.defined
for Recrangleas
well, the differencebetw-een
SquareandRedan;lecouldbe more
readilyseen,^since
Squarc'sperimeterfunction
would be diffirentfrom Rectaigle's.Cuboidis
alsod€riv.:1fromRelraigle,butit expandsrherecordby addingthefield Heigh'i. Furthermore,
with the€dditiooof Height,thefuncrionSizemustbe redefined'forCuboid.-Fina y, similarto
Square,
Cubeisan exactduplicateof its parentCuboid.
Anolherimportant
fe;turcof tagg;drypesis thatnewtypesderivedfrom an originaltagged
-type can
be placedin s€parate
packagesand compiledseparately.This allows foi extenl-ion
withoutdisturbingtheexistirgcodefurtherpromotingencapiulation.
sinceeachclassis contained
wrm,na separately
compttedprogramurul.
Clasg Wide Programmine
. A useful€rrensionof taggedtypesis classwide programmirg. For eachtaggedtyp€T
,
thereis a typcT'Class,to _whichany typ€qerivedfromT canbe converted.This is-viry iieful
becalseit allowsT andall typesderivedfrom T to be passedas parameters
to procedures
or
functions. Furthermore,pointerscaDbe createdto point to; classwid! typedeclaririgthemto be
aypeCiass_Ptr
is acccscT'Class;
primitiveopenuon
The.n
if.a pnmluve
operationIiss calledusing
calledusrtrgeltier
eitherthe
pointeror
the polnter
or theparameter
the programwill
.rnc.ntr,a
rmprrcrlry
choose le operatlonappropnate
to the typeof the classwide object. This choiceof
appropriate
operation
to matcbLheclasswidetypeis calleddispatching.
Thus, as in tbeexamplehierarchyfroq'taggedtypes,i poitir to a classwidetypecould
beassigned
to pornt
poinl to R€ctangle
R€ctanglelirst,
first. th;n
thento Squaie,
Square,tddn
thenCuUoia,
Cuboid.andfinally
finallvto Cube.
;nedio
Cube. After the
polnter is
pointer
rs asslgneO.
assigned,rt
it could
could be
be passed
DaSSed
as a pammeter
Darameterto a Drocednre
procedure
which
whicir.2llc
callsthF
the primitive
23
operationSize on the pointea,and sincethe pointeris
a potnterto
auronraricatty
setects
rheappropriare
Sizefu"iri_ r.i
"*[.i
a class wide rype the program
ir,"i]il;;ii;*,
type Class*ptris acceosRectangle,Class;
Shape_Ptr:
Class ptr;
A: Rectangle;
B: Squarel
C: Cuboid;
D: Cube;
procedure Shape_Size
(Shape:
in out Class_ptr)
is
begin
Size(Shape.all);
ena Sha[_Size;
Shape-Rr.all:= A;
Shape_Size(A);
g;
Shape_ftr.all:=
Shape_Size(B);
-- etc.
Thiscanalsobe-accomplished
withoutthe useof pointers.A procedur€
canbe deiinedso thatits
Thentheprocedure
yjd-e,type.
canbeialedon eachihape
andagainthe
l1:T,:l:r^,:*-1:L1r:
pnmlnveopera[onsarecalledasappropriate.
procedure Shape_Size
(Shape:
in out Rectangle'Class)
is
begin
!izelShapel;
€nd Shap€_Size;
!hape-Size(A);
Shape_Size(B);
-- etc.
notethatwhenusingpoinrers
to classwidetypes,thepointe.mustbe
_ tt is importantto
initializedto point to the valueof theclasswide typewhenslorageis aliocat€d
to it. Thus,in the
exampleprogram,i n orderfor.a poinrerro pointto Recrangle_,
Cnobjectof type Rectangle
musl
rrrsrDeoeltneq,anotnenue potnlermustbetnluallzedlo thatobject.
Dynamic Tvpe Selection
Ada 95 is further€nhaflced
throughthe additionof dynamictype selection.Basically,
dynamictype selectionallows the definitionof pointersto subprograms.Furthermore,
rheie
pointerscanbe usedto passthe subprograms
asparameters
to othersubprograms,
whichgreatly
expands
thecapabilities
of Ada9-5.
Pointersto subprogram
unitscanbe definedin two ways. A pointerto a functionwould
24
bedefinedasfollows
type FunctionPtris accessfunction (A: Typel; B:Type2r...) return
Value-Type:
Thus,Function Ptr is ao accesstvoe to anyfunctionwhich hasa first parameter
ofTyp€1,
second.paramerer
of Type2, etc. dnd retuins a vatueoi Vai"i_iiil.
"a ii,'iriil, to a p.ocedureis
muchsimDlertype Procedurc_Rr
is access procedure(A: Typel; B: T1pe2;..,);
t.*Ou{-"=t]:
rype,ro anyprocedure
whichhaspammelers
of Typel. Type2.etc.
uynamrcll_1"-",T.
rypeserectron
hasa rargevarietyof possible
uses. lt cani; usedto constructa
queueorproceoures
to beexecuted
on a certainvariableor
variables.Orit canallow a procedure
orprocedurcs
based
onsetection
routinei
withintf,"-iiJip-""0ur".er*,
it
l.^:ElE!:-r-fy:,i.":
couro
De useoto createa lunction which callsanotherfunction,passedas a parameter.
reDeatedlv.
Yet.ir is thesimpleelegance
of irsusethali. tt rno.tout"r"noi.ig
;p""it
idi;o;:-**",'
"
Public Children
Ada95-allowspackages
lo besrructurcd
intohierarchic.l
libraries,in whichchlldDackaees
can.DecresleoI romexrstlngpackages.
This allowsfor packages
to beexpanded
withouithen&d
ror recomp rngor drsturbingworkingcode. A publicchild is a child package
which is visible
outsroeortnehlerarchyln which it exists. AlthoughiIs visibledeclarations
do nothaveaccess
to
uepnvarepartot lts parent.a publicchild'sprivatepartandbodycanbothaccess
the privatepart
oI lls Darcnt.
tf for example
a packagetor
floaringpoinr
-^--,9lil991:!g:lareeasilydefined.inAda95.
comprex
numbersexisted,
andwas calledComplex_Numbers,
theha ciild paikagewhichiould
handlev€ctoroperationson floating point compiexnumberscoutdb"
ioiio*.
".""ted'""
packoge Complex_Numbers.Vectors
iI
-Specificationsfor vectorop€rationgon complexnumbers
end Complex_Numb€rs.Vectors;
package body Complex_Numbers,Vectors
i6
--Functionandprocedurebodiesfor operationsin specification
cnd Complex_Numbers.Vecrors.
Then, to use Complex_Numbers.Vectors
in a programor packagca simple,with, statement
is
requfeo.
with Compl€x_NumbeN,Vectors;
use Comptex_Numbers.Vectors;
It is impoftantto note, thatif elements
from the package
Complex_Numbers
were alsooeeded,
thena 'use' st-atementwould
be requircdforCorirplex_Numbers
aiwell,
but
a .with.statement
'with'
wouldnot.b€necessary,
sin-c€
a
statement
is implicitlydeclarcd
for a parent,whena ,with'
statementis givenfor oneof its children.
Oneof the main problemsof the hiemrchicallibra.iesis thatitr o.der to makeuseof all the
packages
within the structur€,a usestatemeDt
for eachpackagemust be iucluded,whichcould
trcome cumbersomewhen
usinga librarywitha largenumberif children,grandchildreo.
etc.or
carrsto chrtdpact€geprocedures.lunctions,
etc.mustbeofthe form:
25
<child packagename>.<name
of typeJfunctionlprocedurcletc.>
Which i a largelibmry would becomeunreadable.
Of course thereare also many advantages
to the hierarchicallibrary structure. The most
.
importanladvanlage
rs the lacl thatexislingcode is not disturbedwhen packages
ere expanded
thrcugh the use of a child p^ackage,
becausithe pArenrpackagedoes nor needriobe recompiled,
whicll n)akesir veryusefulforcrealingclassesforobjeci-orienledprograms.
Addirionally.
pareni
pacKages
canctepenct
on lhelr chtldren.th-rough
tle useof with clauses.andchildrencandepend
on theirsiblings.againthrough
theuseof with clauses.
as wcllas dependon completely
separate
packagesas is nonnal.
Private Children
An_additional
expansiooof the hierarchicallibrary
systen of Ada 95 is the conceprof
.
privatechildren._A
privatechildis.achild unir,in rhelibrarysrructure,
thatis completely
priv;rero
its parentunit. Fufihermore,a privarechild is only visible within rhe subtreero6tedai its parent
unit. And, sinceit is not visibleoutsideof its parent,ssubtree,a privatechild canaccessthe
privatepart of its parent.
A pri^vate
child.isdefined€xactlylike a public child, exceprthe word privateis placcdat the
.
beginningof the specification.Thus if rhechild packageComplex_Numbirs.Vecrorc
was to be
changedto be a privatechild, the codewould be changedto looklike this
private package Complex_Numbers.Vectors
is
-- lrxactlv as fretore
Privatechildren are a useful featureconceptually,bur without a large hienrchicallibrary
structure
to supportth€irus€,the usefulness
of privateciildren is greariydeireased,
complicatin!
whatcouldothenrisebea simpleprogram.
Usingprivatechildrenpr€sents
someproblems
similarto thosefoundin usingpublic
children. First,usingprivatechildrenfurthercomplicates
thehierarchical
librarystructure
which
mustbe maintained,Second,just as in theuseof publicchildren,privatechildrenrequirea use
statement,
andmaybea with statement,
for eachpackage
from thestructure
whichis to beused,or
prefixsystem,ifthe usestatement
a cumbersome
is not included.
Thebenefitof usingprivatechildrenis thatpackagescan
beexpanded
withouttheneedfor
recompilation,
andat thesametimeremainprivateoutsideof thetreerootedat thepackages
parent.
But this aloneis not sufficientjustification
for the useof privatechildren. Theremustalsobe a
complexenoughlibrarystructure
to warranttheiruse.
Generic Children
A genericchildisjust thesameasth€otherkindof children,but generic,whichmeansthat
it canwork for differenttypesof variables,thusmakiogthe childrena lot morefl€xible. For
example,ifyou wanta genericchildof"int€ger,"youinstantiatethe
package
for "integer"andyou
areset.
ThingsI noticed:
Thecompilerdidn'tlet meinstantiate
a child genericpackage
in
insidethemainprocedure
in a separatefile.Sinc€thechildpackage
the mainprogram.Thus they haveto be instantiated
needsto referto thegenericparent,the parentmustalsobe instantiated
in a separate
file. ln the
(instantiation
examplepackage"real_complex_numbers"
of "complex_numbers")
and package
"real-c91nplex-numbersJolar"
(instantialion.
of "complex_numb€n.polar,)
arein separate
files
Notice rhat the iationalesavs to instantiaiep"if"g" ;"6rpi"i_""mbers.polar.
the
followingway
package float_complex_numbers_polar
ir new complex_numbers.polar
This doesn'twork Instead,the packagemust beinstantiatedby
psckage fl oat_compler_numb€isJrolar
is tr€w float_complex_numbers.polar.
. Genericfunctions,procedures,and packagesar€very useful, Tberefore,genericchildren
also v.erylseful. tt is aiso good tharthe]gcnericchildreni;;eu".ess'iJiiJp-rt""te
:j:
ne DalEnt"tem"nt"of
An exampleof a genericchild;
- This is a genericpackage
generic
type float_typeis diAitso;
prckageComplex_Numbers
is
typc Complexic prlvate;
frnction "+" (bft, dghnComplex)
retun Complex;
- similarty"-", "*", a;d '/"
enaL4"xlumters;
packagebody complex_numbers
is
- Functionandprocedure
bodiesfor thepackage
complex_numbers
aoa*mplr -on nU"o;
- Thisis a genericchildpackage:
generic
pickagc Complex_numbers.polar
ir
function Polar_to_oomplex(R,
Theta:fl oat_type)rctu.n C.omplexi
fulction 'abs'(dpht:Complex)return floai tvoe:
function Arg(X: Gmplex) returr floet_rypeJ''
end complex_numbers.polar;
27
package bodJ conrplex_numbers.polaris
--.Function
andprocedure
bodiesfor thepackage
complex_numbers.polar
end complex_nombers.poian
- This is the packagethat conespondsto the instantiation
of
- "complex_numbers"with floais.
with complex_numbers;
package float_complex_numbers
is new complex_numb€rs(lloat)l
This is the packagethal correspondto the instantiationof
-- complex_nrrnrlrrs.polar.
or actuallyfloat_complex_nuDtbers.polar
(b(caLrse
- lhat's lhe packag€
lhatcorresponds
ro complex_numbers
insrantiated
-- lorlloats)-
with complex_numbers.polar.
fl oat_complex_numbers;
packagefl oat_complex_numben_polar
is n€w fl oat_conlplex_nunlbers.polar;
An Exgfnole._of gbiect-OTiented Proerampinq in Ada 95
prograntningin Ada
_ _ _ I he lollowlngexamplereviewsthe mainfeaturesof object,oriented
95. The exampleis an expansion
of the examplegivenin the sectionon taggidtypes.-ln this
examplean abstractbaseclass calledPolygonis created.The classesderived-fiompotygonnave
the following hierarchy
- abstract
ClassPolveon
Data Position_X,
Position_Y
-Set_Position
(X,Y)
Subprograms
Perimeter(P)
l<-
!
ClassTriangle
ClassOuadrilateral
Data- Sl,S2,S3
Data- SI,S2,53,S4
-Set_Sides
-Set_Sides
(S1,S2,S3)
Subprograms
(SI,S2,53,54)
Subprograms
(T)
Perimeter
(Q)
Perimeter
J
Classfueht Trianele
-Set_Sides
(B,H)
Subprograms
Area(RT)
J
ClassRectansle
Subprograms-Set_Sides(L,W)
Area (R)
vI
ClassSouare
- Set_Sides
(S)
Subprograms
Furthermore,in order to show true encapsulation,
eachof the classeswill be placedin a sepamte
package
and lhesepackageswillform a hierarchical
librarysysremof parenrand child packages,
with the packagefor classPolygonas its root.
2A
.. Cla$ hlygon
--+--'---*----,--+ptuksge Poly_Pack
Is
type PolygonL obltrllr
a.gged *fuh
Rlsirioo,* Roar;
Fosilion_Y:FIoat;
and llcord;
proccdurc Set_RNitim (X,y: ln Floati ShaF: out R)l!.gon);
functlon Peridrcr€r(e Folygon) rtltsltr Flo&rls .b6t;r;
end R)ly_Fdc*:
prck{e body Poly-hck I !
proccdurc S€r_Rtsirion(X,y: In Ftodi Shapcrour pdlSq) | s
b.gln
Shape.Position*X:= X:
Shape.PoritiorLY:. Y;
.nd Set_Po8itiooi
end Poly_Prck:
-o'-"----------,o-- Cla$ Triangle
""roi-,____---"_-e!-
prchge Poly_hchTri_Pack I d
typ. Trianglclr nci? Polyton wlth
r.!COrd
Sl, 52, S3r Roat:
.nd ncord;
pmc.duE S.LSidca (A,B,C I n R@t; Shapc:out Triangle);
functlon furimetlr CI: Trianglc) rtturn Flost;
cnd Poly_Pack.Tri_hck;
prck{e body Poly_PaahTd_packI s
proc.dun ScLSid€s (A,B,c: I D Float; Sha!'q out Triangle)I !
bcgl n
Shape,Sl:= A;
Shape.S2
:= B;
ShaF.S3:= C:
end S€t_Sid6;
lun.tlon &rimet€r (I: Trilnglc) fltu]rr n@r I s
begin
Eturn T.Sl + T.S2 + T,S3;
€nd Perimctcq
GndFoly-Pack.Tri_Pack;
- ClassRight Triangle
with AdaNum€rid.Elementary_Functio$; use Ada"Numerics.Elementary_Functionsi
p{ckrge Tri-PockRightTfi-kck i s
type Rightjriangle ls new Trianglcwlth null recoid;
29
procedureS€t_Sjdes
(B,H: tn Fk)ar;Shape:our Righl_Trian8le);
tunction Arca(RTj Rlfhr_TnnglcrrcLurn
Fl ut;
.
erd TriJdcI.RiEhrTri p.r(t I
packrgc bodJ Tri_pack.RjghtTri_p.rck
is
procedureSel_Sidcs
(B,H: in Floar;Shap€:out Righl_Tiangte)
is
b e g in
Shape.S
I := Bl
Shapc.S2
:= Hr
Shape.S3
:: Sqr(B*B + H*H)l
€nd Sct_Sidcs;
function Arctl(RT: Right_Tridnglc)
r€turn Fl(xltI s
begln
r€turn0,-5*BxH;
end Tri_P,rck.RiShtTri_packl
-. Clals Quadrilaleral
peckrg€ Poly_Pack.Quad_tuck
I!
type Quadrilatcml
i s n.$ potlgon wlth
tacord
Sl, 52, 53, 54: FtQr(i
cnd rccordi
proc.dure ScLSides(A,B,C,D:ln FloaqShsps out
euajrilalcral)i
functlon perimcler(Q: euadrilstenil)retum Floar;
erd Poly_FackQuad_Pack;
I!
Packrg€ bod), Poly-Pack.Quad_Pach
proc.dur. Sc(_Sides
(A,B,C.D:In Fbat; Shapqout euadril8tcral)
lE
begln
Shapc.Sl
r= Ai
Shape.S2
i= B;
ShaF.S3:= Ct
Shapc.S4:=Di
end SeLsidcsi
functlon PtrimctcrlQ: Quadrilnlcml)
rcturn Floeli r
begin
Eturn Q.Sl + Q.S2+ Q.S3+ Q.S4l
cnd Perimeler;
end Poly-Pack.Quadj,rck;
--€----------------o*
- Cla.csR..tan8le
packrg€ Quad_Pack.Ret_Pack
Is
type Rectangle
i s new Quadrilaleral
wlth nult recordi
proccduE Set_Sides
(L,W: I n Floal;Shap€:out Re.t$gle);
functlon Are3(Ri Roclangle)
return Roat i s;
€nd Quad_Pack.Recr_Packi
30
peckagebody Q'.4prir.R€clh.*
|6
procedurc Set_Sides
(L,W:i |r Flost;Shapcout R€cranglc)
ts
begtn
Shrye.Sl:= L;
Shape.S3
:= Shapc.Stl
Shapc.S2
:= W;
Shape.S4:= ShapE.S2i
cnd Serjides;
funclion Ar€a (R Reclzlde) rltuft
bcgi||
fttom R.sl . R.s:;
FIGrrI s
lnd Quid_PackRcd_F|ckj
- Cl&s6
Squ{re
p.ckrg€ Rect_hck.Sqr_peck
Is
typ. SquaeI I naw Rccraflgle
wlth hull ftcordi
pro.cdorc ScLsides(Srlr Floar;Shapeout
Erurr);
.nd R€cLR.lcSqr_P&k;
prck.gc body RecLPedi,Sqr_hdtl B
p.oc.dun SeLsides(S: I r Floar;ShapeoutSquarc)I s
bcgln
Shap€.S
I := S;
Shapc.S2:=
Shap€.St:
Shape.S3
:= ShaFE.Sl:
ShaF.S4:= Shrpc.Sl;
.nd SeLsidcs;
cnd RecLPack.Sqr_hck;
--?.-----E--------
e'-
- A poSrarnusingtll€abovectasshienEhy
-o--------------c-w lth RcclPack.Er_P.ck TrijackRightTri_p|ck, TcxLIO;
u3c Poiy-Pack,Tri-PaclqRiShffri_Pack,euad_paak,
Rect_paclq
Sqr_pack.
TexrJO;
proc.duF Examplei s
p.ckagefio l a n€w FloatJo(Floet);
usafioi
proccduruPrintPcrineter(Shapqin Folygoo'Clsrs)
L
b.gln
newJine;
pu(*Th€p€.imeE.of thisshrF is .);
pu(Perimcldshapc),f 3,O);
ncw_line(2).
.nd hintPerimet€r;
.
A: Triangle;
B: Quadrilateral;
Ci Righr_Triengl€;
D: Recralgl€;
E Square;
3l
begln
jdcs(5.(),7.0,3.0.A
Sct_S
):
Sct_R)$on(0.0,t.5.A):
Set_Sidcs(6.t
,8):
Set_Posi0on(_2.0,45,8)
;
Prinrperimctc(A);
Prinrpcrimcrc(E)i
pur('Thcrrcaol thcsqu.rcix ')l
put(Arci(E).1.3,0);
€nd Examplei
This exampleprogramwouldhavethefollowingasits outpur
Theperimeter
of theshapeis 15.000
Theperimeterof theshapeis Z7,?N
The areaof the squareis 46.24O
,
have beenaddedto Ada 95. Theseadditionshave
. In, summary.many enhancements
theforcfront
of prosrammins
languages.
Adae5 has';;;nexpanded
and
::?:gl:i.1"^!:.:! lg
programming
issues,
such
as
objecForiented
prograirming,
and
::T.,lit-.-::,:9Y""1
llny.modem
yers.lr rerarnsrne
secuntyandresdability
of
Ada 93. onceagainAdahasprorlen'itselftobl one
or tnemaJorprcgramming
languages
of yesterday,
today,andiomonow.
ComputerScience495
Object-Orientedprogramming
FaIl 1995
Meeting Time and Place:
Professor:
TR 8:00 - 9:20
VZj.l824
HerbertL. Dershem
Ofhce: WVF 220
Phone:7508
Mailbox;Usemame,,DERSHEM.
Prercquisitesr CSCI 286 andpermissionof the instructor
Objectives:
For the studentto
l. Understandthe principlesof tho object-orientedmodcl
2. Designclassesusing an object_oriented
language
3. Be able to critically evaluaiethe object_oriented
model
Approach:.This coursewill engagethe studentswith the fundamentalsof the object-oriented
par_
adlgm._Itwill be ananalytiaalandcvaluativeapproach.Threelanguages,C++, SmaUtalk,
andAda
95,-will be usedto imprementthis paradigm.stuaenr wrtt aesigi exiensiveciasstioraries
for use
in the HopeCollegeComputerSciencecurriculum.They will alsobe requiredto do
outsideread_
ings andmakepresentations
aboutaspectsof objectoriinted computing.
Textbook: An Introductionio Object-Orientedprograriming by Timothy Budd
Exams:Therewill be a take-homemidtermexam.
Programming ExercisestTherewill be a programmingexerciseassignedin eachof the threelan_
guages,C+r, Arla 95, andSmalltalk.
Project Teamswill completeclasslibradesfor the major classprojectwhich will be due at the
end of the semester.Thesewill be implementedusing C++.
R€portst Eachstudentwill prepareanddeliver a reporton a topic relatedto object_oriented
com_
puting. The reportwill requirethe readingof at leastonopaperon tho topic. Thesereponsare ro
be at leastone-halfhour in lengthandwill bepresentedduring the lastthrcowe€ksof the semester.
Grading:The grading criteria will be as follows:
Midterm Exam
20qo
ProgrammingExercises
2OVo
ClassProject
4OCo
Presentation
20Vo
CSCI 495 - Object-Orientedprogramming
Program Assignment2
Implementa setclassin Ada 95. This classrepresent
a setof Ada strings.This classshouldimple_
ment the following methods:
.
.
.
.
.
.
Make the setempty
Testthe setfor empty
Inserta stringinto theset
Removea string from the set
Pdntthe set,onestringper line
Testa stringfor inclusionin the set
Youareto constructthreefilesfor this assignm€nt.
Filesset. ads andset. adb will contain
rl""in""t:i
b$y.of thepackage
reprcr"nting
tt ct^r. tn
areto w.iteante
1:
""9.
test.set . abdwhich_will.be
" implementation
"Jaiiiin-,-yoi
amainpro$amtotestyour
your_ain
ii
sets.
program
mustdo
.
.
.
thefollowing:
Reada sequence
of strings
fromthefle testinsert . dat andplacethestringsintoa set
whichis initially empty.If a duplicatestringis read,a mes8age
sfroijtJle pnnt"oaf"rtingtt
userthatthestringis a duplicateandtheprogramshouldnot-atternpt
"
to ini"r, ,,.
Nexta sequence
of stringsis readfrom thefile cesErernove. aai. facfr of *resestrings
is
removedfrom thesetasit is read.If a stringis readwhichis notin th"
s"t, -"rrug" to mat
effectmustbeprintedandtheprogramwilinot
to ,"^ou" tt ,trin*"
Arrerbothhlesarccompletelyread,thefinalset"n"rnp,
will b€prinred "
programshouldd€clarea singlcobjectof classsetandprocess
thatsetby callingappro_
I:.main
pflateprocedures
andfunctions.
Attachyourthreefilesto anemailmessage
andscndto ,dershen" befole23:59on october5,
lvvJ.
ChapterX
The Object-OrientedModel in Ada 95
The Ada 95 revisionof the Ada programminglanguageprovidescomPleteand extensiveobject-orientedcapabilities.In this chtpter, thesecapabilitiesaredescribedandillustrated'
X.l Overview
One of the majorobjcctivesof the Ada 95 revisionwasto includea full imPlementationof the
obiect-orienredrnodel.lda 83 includedsomefeatues of the modelsuchasencapsulationthrough
throughtheuseof derivedtyPes'andstaticpolymorphism
of operations
ouit *"i. tto"
"*r"n.ion
with theobject-oriented
Thosefeaturescommonlyassociated
if"offn ouiiio"aine -d generics.
throughthcadditionof datacomponents'
modeithatwerenoifoundin Ada83*ere typeextension
andvisibilitycontrolthatPermitssepastructure,
thesubclass
Jvnarnicpotvmootrismthroughout
All of thesefeatureshavebeen
and
oporations.
to iinre non-publicdata
,.iretv
"tasses
"n"lapioturei
inclided in Ada95.
AnothelobjectiveofthgAda95revisionwastomaintainthefundamentalapProachand.structor"oi *t" eO" t*guage. This objectivehashada major impacton-the implementationof thc obi""i-o,i"ntJ o"r"ais.-in Ada 95: C1ussinheritanccis implementedasa naturalextensionof
*lrif"incapsulation andvisibility issuesarehandledunderthe packagesffuctureof
ii*i"J$*
Ada
_t-t'-","-"ining'".tionsofthischapterdescribcthecompleleimplementatio.nofthoobject-ori83.
entedparadigmin-Ada95. In doing thi;, we do not distinguishthenewly addedfeaturesfrom those
that were presentPrior to Ada 95.
andMethods
X.2 Classes
In Ada, thereis no distilction betweena typ€ and a class This unifies the two conceptsand
makesthe object-orientedmodela naturalextensionof the Ada implementationof the Ada model.
cante
It
9p", ttt"n ar object is any instantiationof that typ€. Therefore,objects
an
object
allocating
"
dynarnically
"
"turrit
variable
and
by
a
createdin two funiimental ways:by de.claring
be
will
vadable
declaration
created
by
of the eivcn tvDeby meansof i new statement.The objelt
to
by
means
refert i to Uv ttrenulneof the variable.Thc dynamically-allocatedobject is referred
oI a pomrer.
of a classare defingdasrecordcomponents.Sincethe classis therefore
fh" d"t"
"o,npon"nt
a recordtype, eachobject of that classcontainsevery dataelementof the class Consider,for examDle.theclassFraccion definedby
tl4)e Fraction is record
numerator : ancelter;
denomiltator : positave;
enal record;
This is a standad recordtypedefinition in Ad4 but it alsoservesto definea class Objectsof t]?e
Fnction can now be instantiatedin the following ways:
-1,
f:
fp
Fraction;
: access Fraction;
1o = ,r"" Fraci:ion;
-ln thii case,both f and tp.aIl' areobjectsofclassFraction
the samecompilation
tllettroasof an laa classare proceduresor functionsihat aredeclaredin
value
belongingto the
a
return
and/or
r"ii* iir" i"ot aiiruration for th; classand haveParameters
to
an oDleclsynbelong
methocls
class.Unliie other languagessuch as C++ and Smalltalkwhere
ofthe
message
receiver
6elo"ngto a class Thereis no objectspecifiedas-the
;;il|;:;il;;t
thereis no specialsynlaxusedto differenliatea receivingob,ecl
rhere-fore.
."rii"" ii,i'n..irr"o,
'-"c:;;""t:;;;".nf
"i'J ilarionunitconuiningihedefinrtion
ofaclassis a packageThe standard
thecomplelespecificatron
(h-erelore
permitling
apply
r i.iUiriiv.oniiof.."ftariismsofthe package
to be hiddenlhroughuseof lhepri vaLe spec'llcallon
of
e classsrructure
"' 'F-;;;pI",
the Frac t i on
;" ,pecificationof a packagedefinrnga few usefuI functronsfor
procedure
p-iiUiting direct accessto the dati of the cliss is shown in Figure X l The
-f,"".i"i
unJ
theyboth
since
Ftaction
ofclass
"f*.
andrhefunctionasFloat a.emethods
funct
ion
The
"-.i..
Frac
package
as
unlittty ut" a""ruredin the same
a-;;;;;";".t.
;";;"-".
The
value
becauseit hasa Fractton retum
is a methodof Flaction
,ion rr-"r..-it".li"n
operator' is alsoa methodof Fractlon
overloaded
-'"'o;;;-,#;;il
ofmethodsis tharon"efuncrionor procep"ssibilityofthe Ada specification
tior" tt'unon" ituss Thiswill only bepossibleif morethanoneclass
d"r"";"igh,;;;;"",:h;ioi
amongits
or functionwhichincludesbothclasses
asa procedure
is definedin the samepacKage
of
classesdenumber
the
convention.keePs
i^i"r""Lr. -Jr"rr" iat'e.-standaidob.lecForienied
will notusuallyarrse
at one'sothissituation
ilaredin eachpackage
''-'i
andtheclass
unit
thatthe encapsulation (in ourcaseFracEioniack)
J""iJ ui
is
in Ada no different
"o"l
se-|arat;entitiesind havedistinctnamcsA methodcall
("t;";i";i;;
thefour methodsof classFrac from anvotheriunctlonor procecurecall Forexample'threeof
tion wouldbe calledin the followingstatement
P!int-Fraction
( f 1 + M a k e - F r a c t i o n ( 5 ' 1 7) ) ;
-2-
Figure X.l Definition of classFraction
is
package FracEiorllack
is Private;
t:4)e Fraction
function uake-Fraction (num. den : i-n inlagef,) return
: in Flaction) t
procedule Prin!-Fraction{F
floati
letuln
in
Fractio$)
:
function as!'l"oats(f
'*'(f1,
Fraclion;
letsurn
:
Flaclion)
f2
in
fuiction
: exception;
Fracti.orLErrot
Flaclion;
t]4)e Fracli,on is record
nunrelator : j.ategef;
! intege!,
tlenoninalor
enal reeordl;
endl Fraction-Iack;
is
package boaly Fractioniack
gackag€ Int-Io
is new ltb€gor-Io
{ inE€Ee! } , uae trtrE-Ioi
funclion Make-Fraction (num' den : in inleger)
!'racbioni
f:
begin
ifalen>0then
:= num;
f,nun€rator
f. denoninaEo! := aen,
elsifaen<0then
:= -nr:m,
f,.nr8r€ralor
;= -den,
f. de[oldnator
efae
raiEc Flact lotL-Erlol t
end lf;
returd f,
€nd uak€-F acEi,on;
(f
proc€tlure Plin!-FracEion
begin
put(f.nullerato!,5);
pur('/")t
pul ( f,. denomii'nato!,5 ) t
end Print-Fracts:ioni
: in Flactlon)
futtcclon asPloaE(f : ia Fraction)
b€gin
floa! ( f ' numerator) / float
return
endl asFloa!;
functlon
result
leturn
leturn
Fraction
is
iE
float
i6
{ f. aleErordlnato! ) ,
'*'(f1
retul.n Fraction
f2 : ln Flactlon)
: in Fractlon,
: Fraction:=
{ f1 . ntltoelato!* f2 . outneralo!,
. alenoninator ) t
f1. dlendrinatolrf2
begin
retsurn resultt
€nal Flactionl)ack;
-3-
i6
X,3 Inheritance
X.3.1 Derived Tlpes and Type Extension
is availablethroughtheuseofderivedtypes'Theclassof thedeA limitedform of inheritance
nor
riuJwpi mavth.n inherirthemethodsof irsparentclass,ovenidethem.or addnewmerhods
all ol lhese
thatilluslrales
anexample
type.FigureX 2 contains
the'parent
oreseniin
'- -1"
Hunan classacrually
The
Mammal.
class
from
is
derived
de clasigunan
it ii
ln the
doesnot apPear
"^rinpr.,
and
Mammal
from
bloodis inherited
Theprocedure
includesfourmethods.
of
lhe
same
procedures
the
speak andgive-name override
definitionof Human.Procedures
get-Iegs
is amethodthatis notinheritedat all fromMaNnal but
function
namesin ua *"f.
is definedfor thefirst time in classHuman'
methodsftom Manmal arestill inheritedby Human'buttheycanonly De
The overridden
a Humaninto a Mallunal Considerthefollowing:
calledby typo-casting
h : Human;
sDeak(h) ; -- thls cal-Is speak from Human
sleax iuanrmar(h) ); -- this call-s speak fron Manma1
for classHumanactuallycallstheMammal
Y-ouwill noticethatthegive-name procedurc
to
its Humanpalameter classMamnal
by tyPe-casting
give-oame
here,If Ma$inal hadbeena p!ivate type,then
VislUitityis'atidanimportantconsideiation
through
namcsThis issuecanbe addressed
gurnanworilanot travehadaccessto thecomponent
will seein SectionX 4'
tho
".' useof childunitsaswe
this form
typesfor inheritance
derived
Permitsextensionofthe,methods'
e-f,tt"ugiirft"
to its
by
adding
"t" "f by havingno capabilityfor exiendrng
thedalaof theclass
ot intr*tariceis timited
the
possible,
Adaintroduces
,""oiJ,iiu"tur". fn o.derio makJthiseitensionof thedataof a class
taggedtype.
,4-
Figure X.2
package Stannal-Pack is
Cype I'Iaxmal is record
, . " r n " , g g 3 i n g ( 1 . . 2 0 );
legs : Natural := 0;
end recordt
procedure blood(fl : in Mannal);
procedure speak(m : in Mannal ) t
give-jnane ($ : in out Masmal; enarae I string);
irocedure
end. I-fanmal-tack
packaEe Eunaq-Pack
tl4)e
is
Huma! is new ![a[una]-;
procedure speak (h . in nunan);
iunccion ge!-legs (h : in tlulnan) rebura Natural;
procedure give-lrane (h : in ouE llunan; tnnane I string);
end HumatLPack;
package boEf EumaD-Pack is
procedure speak(h : iE Huna!) is
begin
put-1ine {h.rrane & "says 'hi"')t
end Epeak;
f,unction get-1egg (h : in l{uman) return Natural is
begin
regurn h.legE;
end get-ldg€;
glve-nane (h : 1!I out Hrman; rnnatne : String)
pro."dut"
begin
give-nane (Maeal (h) ' rnnane) ;
h.1-egs := 2;
end give-name;
end Human-Pack;
is
X.3.2TaggedTlPes
Themaiorlimitationofderivedtypeswithrcspecttotheobject-orientedinheritancemodeliS
the
the aooareniinabilitv to extendthe dataof a class.Forexample,supposewe wish to include in
.
Natural
n,r.ll.tass ttrat*as defived ffom Mar*nal, anadditionaldatafield called IQ of type
This
- - rs not possiblethroughlhe useof the derivedIypefealure'
t yl e x t e n d i n g t h e d a l a o l a d e r i v e d t y p e b y a d d i n g n e w d a t a e l e m e n t :
e a u i n " i u a . .r t t " . u p a 6 r l i o
tyPe This is doneby declanng the basetype to be
bevondthosepresentin the corresponding-base
to Human' we coulo
tagged.For eximple. to accompllshour goal of addinga datacomponenl1Q
.leclarethetwo classesas toilows:
t]T)e Manmal is tagged record
name : String (1. .10 ) ;
:= 0;
leqs : Natural
end record;
t)4)e Human is new Manunal wiLh
IO : NaLulal;
end record;
lecord
datacomponentsof Mammrl
Thesedeclarationsindicatethat type Human inheritsboth of the
(name and legs)and addsone new component'IQ
"'*iJ*...#.i.""an
rebe applied from the derivedtype to irs taggedparentsince it simply
from taggedparentto derived lype reoutr"J ifr'u,,ita .u.piut componenrcbe dropped Convorsion
followingexample
considerthe
however'
beipecified,
ilil ;;; ,tr;;eI;i;nal c6mponents
in bothdirections:
conversion
i'ilustrating
rn1
htm2
h2
Manma1( "manrmalname",2) t
H u n a n ( " H u m a n n a n e "' 2 , I 2 4 ) i
Marnma1 ;
Hunan;
m2 = Mar.mral(h1) ;
b 2 = ( r n 1 w i t h I Q = > 3 0) ;
withn2 takingtheManunalsubset
typeconversion
fromh1 tom2is standard
Theconversion
ofall components
thedefinition
fromm1 totrz requires
lri. Th" connersion
d;;"J;;i;;;
of theconversion
"f
;;";s butnotin thebaseclasswhichis thesource
;i";;"ii'il
"'''fn"
outto multiplelevcan
becarried
types
ttteuseof ragged
i"ri""il"" Jsuuaasse.tttrougtt
fromllusubclass
asa
newclastttiltl:
we-have.a
suppose
els.Forexample
]lilt:"d:rived
sucnas scnoo_Lcrru
man.The classsEudent wlll addsomedatacomponents
The class student is then declaredby:
v!"t-i"-t"rt"ol.
tvoe Student is new tluman wiLh record
school : string (1' 20)'
: PosiLive;
year-in-school
end record;
type
byFigurcX 3 Eachncwd€rived
is illustrated
to eachof thethreeclasses
Thedatabelonging
,6-
may, of course,provideadditionalmethodsaswell asadditionaldatA throughthe normaldedved
tvDe
-' ' facilitv.
Sp".iot'.on"ia..ution is Sivento taggedtypeswhentheyareprivate typesasweII' As usual'
private
tagged typeshavetheir componentshiddenfrom extemalunits-'It is requircd,howtagged type be privateaswell In the aboveMaJniver, that all typesderivedfrom a private
tagged
rnal /ffumanT student example,Mammalcould havebeende'lared asa private
type asfollows:
cl.pe Mammal is tagged Private;
nri.'"a"
tl'pe Marnmal is record
narne : Strinq (1. .20) ;
Legs ; Natural;
end record;
Then Humanmust be declaredas a pdvateextensionofManunal by
b!T)e Hurnan i5 new Ma[unat with
prlvaEe
tlt)e Human is new Marnmal with
IQ : Naeural;
privabe;
record
:::'"'o'u
In this case,all componentsofManmal areinheritedby Human,sowithin the packagewhereHurnan is dcfined,referencesto anyof the compongntsofMaNnal arevalid. Therefore,insidethe
packagecontainingthe definition of Human' we canwnte
h : Human;
_"j
n.legs := -L;
andthe referonceto datacomponentlegs, definedin !{arrunal, is legal' A rcferenceto tr asa
Marrunal,however,would noapemit dft€ct rcferenceto its dalacomponents,sincethe Manmal
comoonentsareDrivateto the pickage in which Maqunal is dofinedand''ot accessibloin thepackaeewher€Humin is defined.bf course,this would not be the caseif both HumanandMarnmal
*i"r" d"fin"d in th" t"*" package,but this is ','otconsideredgoodobjelt-orientedpractice.Therefore, if the two classesare definedin separatepackages,
Ma{unal(h) .legs
:= 2;
is illegal insidethe packagewhcre Hu.lnanis defined
-7 -
FigureX,3
Manmal
Human
student
nane
Iegs
nalme
nane
legs
IQ
school
year-in-schooL
X.3.3VisibilitYand Child Units
practicein Ada is to doclareoneclassperpackageOnedifficulty with thisapThe standard
model'the
withtheobject'oriented
associated
oroo"t i, ittutln oiO"tto maintaintheencapsulation
notvisibleto the
ii"* ,'fl"riJ!" a""f."d asa privatetyPe.ihts meansthatthedataofoneclassis
methodsof anyotherclass.
-sectionthatindeclaredin thepreceding
otthis rest ction,considertheclasses
a" un
package.
in
a
different
is
declared
"*rri-rpt"
each
that
andstudenL andassume
u"^."rjg"."n,
"rui"
For example,
-Dackaqe Ma$malJack is
tyPe tcarunat-ls tagged Private;
ent Mammaliack;
use Marunaliack;
wich Marunaliack;
package
Humaniack is
'
tgr! utt .t is new Mammalwith private;
e'rJ H',.unj.ck
with MaNnal-Jack, Humaniack; use MaNnaliack'
is
-package Studentiack
t1p! student is new Humanwith prj'vaLe'
"nd
Humaniack;
Scrrdentlra.k;
of Manunalaredeftnedin theprivate sectionof
Now, sincethedatacomponents
them what weneedis theabilitvfor
ttumancandirectlvaccess
whereits parentclassis
theprivates;ctionof thepackage
tfi" *Uclassto access
";;i;;;k;;;;;thod^of
ifr!p""t"i"
"i
*"'Tiis
defined.
a packageis a childunit of
capauititvis providedin Ada by meansof childunits when
visiblewithintheprivatesectionof the
t"Jf"t",-i, tift"s theparenfspiivatedeclarations
"..'fr"r
ctrilJoaitae.It"hictt includeslhe bodyof thechildPackage
has
'ts namelf theparentpackage
through
or unother
ii d*iui"a to ut u
jta
This
naming
P
"t'iraP c wouldmak; chill,f^*T1:f
a pacKage
namrng
nameP,for example,
nameP c Gwouldbe
a package
ouito muttipi"ievelsForexamples'
;;;;;";;;;;;"rii"o
of P c
a childpackage
""'ffi;ffkjg;
-8-
visibilityfor subclasses.
In theexareveryusefulforprovidingtheappropriate
Childpackages
named
amDleabove.classHumancouldbedeclaredin a package
in
MarnmalJack - Human--packandclassstudent
Humaniack. student--pack. Thenall memberfunctionsof classHrman
Mannaljack.
of Marunalthatareinheritedby Human.
couldaccessname and1egs, privaLe comPonents
private
elements
of bothManmal andHuman.
all
Likewise,student couldaccess
Although typeextensionandchild packagesareunrclatedconcepts,the first havingto do with
thesecondwith visibility,theyareoftenboundtogetherasin our Manunal/Hu
inheritanceand
in a packagewhichis a childof thepackman/ student example.By alwaysdefininga subclass
of theparentclassaievisibleto the
agedefiningits parenttype,weensurethatall privateelements
child class.
X.3.4AbstractTlpes
gxistonly to providea basefrom whichotherclasses
caninherit.Suchclasses
Someclasses
thatwill have
have
de
vedclasses
exist
to
directly,butrather
neverhaveanyobjectsinstantiated
instantiations.
In Ada, this propertycanbe enforcedby makingthe classan abstracttype. As anexamPle,the
classuarnrnat,whiih wasdefinedearlier,couldhavebeendeclaredasan abstracttype.This can
be doneby thefollowingdeclaration:
C]4)e Marunat is abstracE taqged privaee;
nameand1egs, andprocecaninheritdataelements
ClassMarnnalexistsonly sootherclasses
of typeManunal.AIso'
duresblood andgive-name. No objectsshouldeverbe instantiated
be redefinedfor each
but
should
to
be
inherited'
is
not
intended
procedure
speak
notethat the
sPeakin classMamto
actually
define
necessary
classderived-fromManrnal. Therefore,it is not
be
abstract:
nal. This canbe indicatedby declaringtheprocedurcspeak to itself
procedure speak(m : in Mannal ) is abstract;
The astutereade!will noticathat it appearsthat speak would not needto bedefinedat all in Mamcanbe useful
we will seelater,however,how absfiactprocedures
ma1 sinceit is neverinherited.
for dynamicbinding.
Our new definition of Marnrnalas an abstractclassis now found in FigureX.4.
Figure X.4 Abstract Versionof Marnmal-Pack
packaqre Mat$mal-Pack i5
!)pe Mamnal j-s abstriacE
procedure
pr.oceatute
procedure
tagged
bloodlrn : in Ma]nn'a]),
speak(m : in Manmal)
erive-nafre (m : in out Ma$ma1; Mane
l)4)e Mamnal is record
naltle : Slxins(1..20);
:= 0;
leqs : Nalural
end Manmal-Pack
-9-
: sclinq)
X.4 ControlledTlPes
execute
codewhenobjectsof a classarecreatedor
Ada providesthe abilityto automatically
of C++.In Adq this is handied
to
the
constructor
and
destructor
destroyed,
similarin function
Initialize
andFinalize, thataredefinedin a built-inabstract
throughspecialprocedures,
ize and/orFinalj'ze aredeany
class
for whichInitial
classcalledControl led. Hence,
will be calledat oblhat
rnitialize
insuring
finedmustbe a derivedclassof controfled.,
ject creationandFinalize on objectdestruction
of
Adjust, is providedin classconcrolled to facilitatethe sequence
A thirdprocedure,
thatne€dsto occurduringassignment.
creationanddestruction
rni tial i ze is calledwhenfrom controlled, theprocedurg
is
derived
Foranyclassthat
procedure
of
a
control Led typeis called
ize
The Initial
evera newobjectis instantiated.
in thefollowingsituations
whichdoesnot includean initial
by a declaration
1 Whena iariableof thetypc is declared
value.
typewhichincludesthecontrol led
2. Whena variablois declaredto be of a composite
classin its definition.This inclusionmaybeeitherdirector indirect.Again,if thecontrolled
i ze will not be
containingit is initializedin a dc{laration,rnitial
objector anycomponcnt
called.
classor
for anobjectof thecontrolled
3. Whenan allocatoris calledby a nsw statemont
acompositeobiectcontainingsuchanobjoct'Again,ifaninitialvalueisspecifiedfortheobject
rni t ialize will notbecalled.
in rheillocarionstatement,
control led' therni cialthatarethemselves
objects
If a concrol led classcontains
izeprocedureforthecontainedobjeclsarecalledbeforetheconlainingobjects'TnitiaIj-zes
definedin Figure
orderis illuitratcdby thethreecontroLl-ed classes
ur. ciffia. ffris
"afUng
i.ze for childl is calledfirst
6'i classparent is detlarcd,theInirial
oUj""t
iS. Wt
for Child2 will notbe calleduntil the
of parent. The Initialize
,in"" ,t i,"n "n
parent
" "o*rion"nt
wheretheallocatorfor chitd2 is exe.cuted.
i ze for
ii, Initial
ifrirJ,t""*"",
'-'-'it
at thetime an objectof that
procedure
of a controlled classis executed
ri"":.i""
blockcontainingthedeclathe
execution
"
thisis whcn
i'or declarcdvariablcs,
to
c""."s
"tass
not aynamicallyallocatedobjects,it is arthetimeofdeallocationA FinaLizat"ti* ir iilt"a. "^ist.
to anobje'l thatwould
pto;idedto fr€esioragethathasbeenallocated
it
ai." i*"i"t"
by rheobreferenced
of rheobjecr,suchassrorage
,he'nirmaldeallocation
i""]i"*"JUV "Jually
"-ot;"
iect'spointers.
'--'a
andFinalize is foundin FigureX 6 A List classis
i"Ji"i"*u-pr" of rnitialize
sets
definedin thisFigure.Notethatthe list includesbotha headandtail pointer'Initialize
theList itself
inthelistbefore
upallofthenodes
f *hile Finalj.ze frees
U"iii'p"i"i"ii"
",it
is deallocated.
t0-
Figure X5
wirh
Aala.Finali.zation;
use Aala. Finalization;
is
package Test-Init
lrith ptivate;
new
controlletl
is
Cbifdl
typ€
l|'ilh privatet
ts!'pe child2 is nelv Controlled
!14)e Parent is new controlLeal nith privalet
priwate
q'pe childlptr
ie accese atl cbildl t
is acces6 chilal2,
tlpe cbildzpt!
witb record
tttl)e Chi.1d1 i6 new Contlolledl
Data r lntegert
siblinsr : cldld:lptr;
t)4)e chj.l"d2 is new controlledl
Data r Integet;
r Chtldlplr;
Sibling
enal recoral,
lype par€nt i6 new co4tlolled
First
: atiased Cht1d1,
second : child2ptr,
endl record;
procedtule fnitj.alize{cl
procealure htcialize(C2
procealule Initiallze{P
enal Teat-tnitt
with
record
with
recoral
: in out childX,,
: in out Child2);
: in out Farent);
iE
gackage body Test-Inlt
: in out childl)
procedlure Initlalize(c1
begin
,
Put-line ("chl1d1 Inltlalize')
cl,.Data := 1t
null
cl.slblins:=
etd Inlllallze;
i3
: in out ChlLiU)
proceiluie Initlalize(c2
begin
t
Put-IJine ( "chi1d2 Inirialize')
C2.Da!a:= 2,
c2.sib1lng :- ltuU i
end Inltialize;
is
plocedule higlalize(P
: in out Par€lrt)
b€sin
Put-!,ine { "Paren! Initialize');
P. FirsE. stbling : = P.Second;
P,second := new Child2,
:= P.9l'!68'Accessi
P.second,sibling
end lllitializet
enal TeEt-Initi
is
-ll-
Figure X.6
with Ada . Final izaEion;
use Ada. Finalization;
package Lis!-Pack
is
with privale;
tl.pe List is new conlrolled
procedu.e Aald-lo-Fron! (L : in out Lis!; r : in Inteser);
procedule Add-Lo-Rear (L : i. oul lJist, I . in Integer);
second i ilt LisE) reluln List;
fuction
"+"(First,
r:"(Firsr,
Second : in List) rerurn BooLean;
function
procedure Pul(1, : in l,ish);
!l'pe Nodet
is access Node;
t)rpe NodeJlt
!)Ee Node is tecord
Daca : In!ege!;
Nex! : Nodeitr,
end recordi
with
!]4)e Lis! is new conllolleil
Head : Node-PCr;
Tail I NodeJlr;
record
: in ouu Lis!),
procedure Inilialize(L
procedute Adjusl(L I in ouc List);
: in ou! Lis!),
proceilure Finalize(L
end l,ist-Pack
package bodY List-Pack
procedule Ini!ialize(L
begin
Pu!-t ine ("Ini.liaIize
L.Head := null i
L.TaiI := nul];
end hili.alize;
is
r in oul List)
is
called') ,
procedure Adjust(L : in oul Lis!)
Tenp : NodeiEr := L.Heaat;
is
Puc-Line ("Adjusl called' ) ,
Pul(r,);
L.Head :- null;
L.Tail := nuII;
whiLe Temp /= null loop
Add-to-Rear (tJ,TemP.Data),
Tetnp := Terip. Nex!;
elrd loopt
end Adjuec;
; in oul Li6!) is
plocedure Finalize(L
is
new
Free
Drocedure
Ada . UncheckeLDeallocation
:= L lleadi
Temp : Noaleitr
Node--pE!;
save :
begin
call-eal" ) ;
Put-Lilte ( "Finalize
PUE{L) ;
whiLe Teq) /= null loop
Save := TenP;
12
(Node. Node-ilr
)
Temp := T4p.Next;
Free(save);
enCl loop;
L.nead := nul ];
L. Tail := null;
end Finalize;
end List_Pack;
X.4.2OverridingAssignment
oporator"::' is definedin FigureX.6.Whentheassignment
An assignment
components
of L2, Head andTail, arecopiedto thecorresPonding
thecomponents
is executed,
ofL1. This meansthatLL pointsto thesamelist asr,2 ratherthana copyofthe list.Usually,this
is not thecopythatwe wantsincea laterchangeto L2 wouldalsoresultin Ll beingmodified
classforjust thispurpose
in thecontrol led abstract
Ada providestheAdjust procedure
for a Controlled class.The assignexecuted
duringeachassignment
Adj ust is automatically
of operations
for thestatementope€tionalsoresultsin a Finalize beingcalled.Thesequence
ment
is asfollows:
l. Finalize(Ll) is called.
of L2 arecopiedto L1 asin thedefaultassignment.
2. Components
3. Adjust (L1) is called
As a result of this scquence,the Adjust procedureis written underthe assumPtionthat the
componentsthemselveshavealreadybeencopied.Any further adjustmentsmustbe madeby the
Adjust procedute.
The Adj us t procedureshownin FigureX.6 implementsassignmentfor the L i s c classof the
Head andTai1, havealreadybe€ncopiedprior to
precedingsection,Sincethetwo components,
assumes
thatthesepointto theList thatis on theright-hand
ahecall on Adj ust, theprocedure
creates
a copyof thislist,andsetsHead andTail to
Adj
ust.
Plocedure
sideof theassignment.
placesin thiscopy.
point to the appropriate
X.5 Polymorphismand DynamicBinding
all types
types.Thesetypesrepresent
in Adathroughtheclasswide
is achieved
Polymorphism
Classwide
types
alsoperpsrmit
types
in
the
hierarchy.
referenceto all
in a subclasshierarchyand
mit the dynamic dispatchingof a subprogramcall.
Tlpes
X.5.1Classwide
Every taggedtr?e hasa correspondingclasswidetype. The classwidetype of type T is written
hierarchyof
of anytypein thesubclass
T, class. ThetypeT'class permitsthercpresentation
T. For example,supposetaggedtype T hasthe following subclasshierarchy:
Humfn
Caiine
Then all five of the types have a conespondingclasswidetype.The following table indicatesthe
rangeof reprcsentationofeach classwidetype.
Classwide Tl4)e
Mammal'class
Human'class
canine'class
Dog'class
Wolf'class
G,no
F6hr6c6hiorl
Mafiuna1, Human, Canine,
Human
canine, Dogr, wol f
Dog
w o1 f
Dog, Wolf
Variablesmay be declaredto
contexts.
typescanonly beusedin certainrcstricted
Classwide
For example,
provided
in
the
declaration.
value
is
if
an
initial
type
only
beof a classwide
x : Mafimal'class
wouldbe illegalwhereas
d : Dog;
x : Manmal'class := d;
typemustalwaysbelongto oneof thetypes
anobjectofclasswide
is legal.Thisis thecasgbecause
Therefore,
Oncean objcctis boundto thattypeat its creation,it maynot.change,
it cai represcnt.
'
cannot
be modiDog
and
that
it
is
a
its
tag
indicates
c
tass,
thoughx aboveis of typeMa$mal
fied oncethebindingtakesPlace.
typ€canpointto differentobjectsandthereVariableswhichareofaccesstypeto a classwide
thefollowingcodefragment:
Consider
timcs
tyPes
at
different
different
forepointto objectsof
t)4)e namptr is access Manmal'classi
mp : ma.nptr;
np := new Human;
;p
:= new Dos;
will resultin np pointingto a Hunan objectfirst andthona Dog object'
X.5.2ClasswideSubprograms
Aclasswidesubproglamisanyprocedureorfunctionthathasformalparametersthatareofa
maybeof anyof thetypesrepresentfor sucha subprogram
type.The;ctual parameters
classwide
typeitselt
tyPeor belongto theclasswide
ed by theciasswide
by
defined
same-species
Considerthefunction
' c ]'ass ) return
function same-species (ml, n2 : l'lanrrna1
begin
'
return nl'tagt = {i2 tag;
l 4-
Boolean is
end same-specles;
This ftrnctionis a classwidesubprogrambecauseits parametersareof classwidetyps. It alsointroducesthe t'ag atkibuteof anobjectof a taggedtype. Two objectswhosetagsarethe samebelong
to the sametype withir the classwidetype sincatheir tagsidentify thsir type.
The function same-species canbe called with actualparametersthat belongto any of the
typesrepresentedby Marmal ' class. For example,if variablesaredeclaredby
type mamptr is access lvlannal'class;
dog;
= Maiunal"'class := d;
h
Humant
m
manprr;
d
Then all of the following calls arelegal:
-.
>atrc_>PeLrer
\u,
rr/
...
.- same-species (x, h) ...
... same-species (m.alL. x) ...
The first two calls will retum false while the result of the third call dependsuponthe type of the
object to which n points at the time of the call.
X.53. DynamicDispatching
While classwidesubprogransprovide somedegr€€of polymorphism,anotherapFoach is dynamic dispatching,This occurswhen a singlecall to a subprogrammay be dispatchedto multiple
haveformal
subprograms,dependingon the tagsof the actualparametcrs.Classwidesubprograms
parameters
actual
of
classwide
paramJtersof classwidetype! whereasdynamicdispalchingutilizes
typ€s.
An exampleof dynamicdispatchingappearsin the followilg fragment:
n : mamptr;
speak (tn.all ) t
Sincethereare speak procaduresfor both Dogs andHunans, thecall to speak could actually
result in eitherof the two beingcalled,dependingon the tag of n . af 1 at thetime speak is called.
If thoreare multiple parametersof classwidetype, the disPatchingcanbe basedon the combi
natiol of tagsof the parameters.The reulm valueof a functioo canalsodrive dispatching.For example,supposethc following two functionsaredefined:
create-narmal (name:sering)
function
m : mamptr := new Dog;
begin
give-na$e (m.all. name) ;
return Dog(m.al,l),
eltd create-marunal;
function
create-maflnal (name:sLring)
-15-
regurn
dog is
return
Human is
m : namptr
--Gv.-n.
:= new Human;
( * . . 1 L , n a m e );
"
reburn Human(m.al1);
end creaEe-nannal;
Then the call
m. all
:= cteate,nanunal ( "'Joe') i
dependingon the tag of
would dispatchits call to the apPropriatccreabe-matonal' function'
m .a l l .
CSCI383
ProgramAssignm€ntE
An ObjectiveLook at tula
D[e Novembern '1996
below:
described
Youareto implernentthefrveclass€s
ClassDate
InstanceVariables: Month,Day'andYear
InstanceMethods:
Set-Datc(3 naturalpanmeterspluslhe rcccircr)
Get-Month
Gtt-DaY
. Gct-Year
Put
ClassTiansaction(abskact)
(Date)
InstanceVadablcs: Dateof hansaction
l0))
AccountNumbcr(Stdng(1..
(lvlonoy
typc= 6616g'01digist8)
Amountof Ttansaction
InstanceMethods:
(3 parametirsplusther€ccivcr)
Set-Ttansaction
GGLDate
GetJcct-Num
G€t-Amt
Put
ClassCheck
Transaction
Superclass:
InstanceVariables:
Checknumbcr(Natural)
Peyce(Unbound€d-Stdng)
InstanceMethods:
Set-Check(5 PalametErs
PlusthcrceiYer)
GeLCheck-Num
Get-PaYe€
Put
ClassDeposit
Transaction
Supcrclass:
InstanceVadabl€s:
(String(1..5))
Branch-Code
InstarceMethods;
Set-Deposit(4 panmetersplustherec€iver)
Get-Branch-Code
Put
ClassAccount
lnstanceVariables: Balance(Money)
,
InstanceMethods
Name(Unbounded-String)
(linkedlist of all transactions)
T.ansaction-List
Initialize (startbalanceat 0 andlist asempty)
Finalize
Add-Transaction
Put (print all tmnsactionsin list orderedby date)
Get-Balance
Cet-Name
Set-Name
Clear-Transactions(emptytransactionlist)
restprogramfile shouldbe submitted
The filescontainingthoseclassosalongwith a menu-based
by 12:00p.m on November2?, 1996No latePrograms
to anemailmessagc
asan attachment
soturn in whateveryou haveby thedQadline'
will be accepted,
cscr 383
Program Assignment9
Merry Christmas to All
Due December6. 1996
SantaClaussleepsin his shopuP at the North Pole, andcan only be wakenedby either all nine
reindeerbeing back from their year long vacationon the beachesof sometropical islandin the
SouthPacinc,or by someelveswho are havingsomedifficulties makingthe toys Oneelf's Prot)lem is neversedousenoughto wakeuP Sant4 so, the elvesvisit Santain a group of three' When
threeelvesarehavingtheir problemssolved,anyother elveswishing to visit santa must wait for
thoseelvesto retum after Santahassolvedtheir problems.If Santais awakenedby both three
elvesandthe last reindeerretumingfrom the topics, Santahasd€cidodthat the elvescan wait
until after Chdstmas,becauseit is more importantto get his sleighreadyassoonaspossible'
You are to solvethis prcblem using Ada tasks.You areto creatsthreetask types'ReindeQr'Elf,
and Santa.Define thesetask typesand anyothe! itemsyou needin a Packagecallcd Task-Pack'
In your main program,you will declarea Saatatask andan aray of nine Reindeertasks ln addition, you will havein your main programa pointerto an Elf taskandcreatea new Elf task every
time an elf hasa problem.Your programwill be menudriven andthe menupresentedto the user
will appearasfollows:
ChristmasMenu
l. Reindeerarrival
2. Elf hasa Problem
3. Checkreindeerstatus
4 CheckSantastatus
solved
5. ElvesProblems
6 Santaretumsfrom Christmasdelivery
7. TerminateProgramand all task
When selection1 is made,the programshouldpromptthe userfor the reindeernumber(1.'9) and
keeppFompting until a valid numberis entered.If the specifredreindeerhasalreadyanived, a
mesiageshoutdbe printedandthe menureappear.Whcn selection2 is made,a new elf task is creatcd ;d that ctf goesto Santawith a problem.When selc.ction3 is made,the locationsof all nine
reindeerarereportcd.Whenselection4 is made,Santa'sstatus(sleeping,solviog,or delivedng)is
reporte.dandthe numberof elvescurrently waiting for problem-solvingis printed.when selection
5 is made,Santaleavesthe solving modeandrctumsto sleeping.Whensele.tion 6 is made,Santa
returnsfrom deliveringmodeto sleeping.In the cas€of selertions5 and 6, if Santais not in the
pertinentmode,a mossageis printed andthe Menu reappea$.When selection7 is made,the program and all tasksareterminated.
This programis to be submittedby email by 12:00p,m. on Decernber6' 1996'No late programs
will be accepted,so tum in whateveryou haveby the deadline.
CSCI 383: Programming Languages
Fall,1996
CourseSyllabus
cs
Sur
Ianguages- MWF 12:00-12:50,IZN824
38j: Programming
Control
of programminglanguages.Programminglanguagesyntax Theory.ofcomputation
Ianguages
Applrcatrve
es- Reiursion. Languageextensibility.Application languages
^^.
ComputerScienca225'
in Ada Prerequisite:
programming
Experience
t-orientedlanguages.
years.1996-97.
ve,r:objectives arefor the studentto
l . Know andunderstandthe fundamentalPropertiesof programminglanguages'
languages.
2. Be ableto effectivelyleamandutilizenewprogramming
andbeableto usememlanguages
programming
of
3 . Know thefive majorparadigms
4. Be ableto choosean apPropriatelanguagefor a given application'
Jipping
Text ProgrammingI'angul1es: Structuresand Modets,2nd Editianby Dershemand
edu
.' Herbed L. DershemI YN 22O1 75O8I dershem@cs'hope
: ImDerativeandConcunenvParallellanguagefeatureswill be illustratedby the Ada
$ith the variousfeatures
will programin Adato-gainexpe.rience
Students
ing ianguage.
iiii
"itoG.
Prolog,smalltalk'and
gxn"a in languaglsof othermodilsincludingScheme,
isire. ComputerScience225
.' Therewill be threeexamsin this class,tentativelyscheduledasfollows:
Exam 1 - September27 in class
Exam 2 - October30 in class
Final Exam - DecemberI I at 2:00 P m
. Frequentassignmentswill be given, including writing progralnsin tho va ous languages'
in| Criteria:
Exam l: lOVo
Exa'Il2|lOEo
45%
Exercises:
Programming
Homework:157o
FinalExam;2070
CSCI383:ProgrammingLanguages
Fall, 1996
CourseContent:
Aug28
Assignment
Textbook Readins
Date
I Overview,&Iistory
4!gi9 LL19j-1'ryg'*
l{W I due
Sep2
3.I DataTypes
Sep4
3.2ExecutionUnits
Sep6
Sep9
3.2-3,3Exec.Units & ControlStructures
4.1-4.2DataAg$egates- Anays
S e p1 t
4.3-4.6Otheraggregates
P.ogramI due
Program2 (Ada)
Sep13
Abstraction
5.1-5.3Procedural
HW3 due
p. 131
1,2,3,
Exercises
Sep16
5.4Parameters
Sepl8
5.6-5.7FunctionsandOvorloading
Program2 due
Program3 (Ada)
Sep20
Data Abstraction/Paramoterization
LabEx. 1-5,p. 172
Sep23
Sep25
Ada Packagesand Generics
C ticalIssues- No class
Sep27
ExamI
Sep30
Model
Functional
9.1-9.5
Oct2
9.6-9.?FP
Oct 4
Scheme
10.1-10.2
Oct 9
10.3Scheme
Oct ll
10.4Scheme
HW6 due
due
AdaJournal
Oct 14
12,l- 12,2l-/|gic-OrientedModel
Program5 (Scheme)
Program4 due
ProgramI (Ada)
1,2p. 48
Exercises
3 due
Program
4 (Ada)
Program
Oct 16
12.2A PureIrgic Innguage
Oct l8
l3.l Prolog
Oct2l
13.2Prolog
Oct23
13.3kolog
Oct 25
X.l Introductionto Object-OrientedModel
Oct 28
x.2 smallralksyntax
Nov I
Exam2
Nov 4
X.3 Moresmalltalk
Progmm7 (Smautalk)
Nov 6
Y.l Ada 95 andthe Oo Model
Program6 Due
Nov 8
Y.2 MoreAda95
NoYll
Y.3 Still moreAda95
Nov 13
Y.4 Ada95 adnausoum
Nov 15
Model
17.1-17.3
DistribuledParallel
Nov 18
Nov 20
MoreD/PModel
17.4-17.6
Unitsin Ada
I 8.1-I 8.2Concurr€nt
Nov 22
18.3MoreConcunentAda
Nov 25
Ada
StillmoreConcurrent
18.4-18.5
Program9 (Ada95)
Nov 27
in Ada
18.6Examples
8 due
ProgramAssignment
Dec2
Review andcatchup
Dec4
Reviewandcatchup
Dec6
Reviow
Program6 (Prolog)
Program8 (Ada95)
Program7 due
ProglamAssignment
9 due
Hooe Colleqe
Deparanerlit oJ @mpriiter
Science
I{ollqnd, Mich;igan 4 I 4 2 2'9 OOO
(6'76, 395-7510
March 13, 1997
DavidR. Dietz
PWS PublishingCompanY
20 Park Plaz,a
Boston,MA 02116-4324
e@pY
DearDavid:
It wasgood to mect you in SanJoselast month.Mike Jipping andI havecompletedthe chapter
overviJw of the Third Edition of our textbook.As we discussedin SanJose,I am sendingthat to
you asan enclosure.
If you haveany questionsor ne€dany further informationat this time, pleaselet me know
Sincerely,
HerbeltL. Dershem,Chair
and Models'
Programming Languages:Structures
3rd
Edition
Herbert L' Dershem and Michael J' Jipping
Chapter I - lntroduction and Overview
is unchanged
ThischaPter
Chapter 2 - PreliminarY ConcePts
is unchanged
Thischapter
the Imperative Model
Chapter 3 - An Overview of
of Ada95
of features
exceptfor theaddition
is unchanged
Thischapter
ChaPter4 - DataAggregates
ttre additionof featuresof Ada
This lhapter is unchangedexceptfor
95
Chapt€r5' ProceduralAbstraction
Ada 95'
exceptfor the additionof featuresof
This chapteris unchanged
ChaPter6' DataAbstraction
of Ada 95
exceptfor the additionof features
This chaPteris unchanged
Model
Chapter 7 ' An Overview of a Functional
changes
Editionwith no significant
This chaptorChapter10of the Second
Language
A Functional-Oriented
ChapterE' Scheme:
changes
Editionwith no significant
This chaPterChapter1I of theSecond
Language
Chapter 9 - ML: A Tlped Functional
changes
Editionwith no significant
This chapterChapterI I of the Second
Model
Chapter10' Prologand the Logic-Oriented
ThiseliminatestheuseoftheLPlanguageandintroducestheLogic-orientedmodelthroughPro
ou"t tttarin chapterl3 of the secof P'orogo g'"uti;;;"p-u;al unJi*p'ou"a
loe.Thecoverage
on-dEdition.
Chapter ll - Smalltalk and the Object-Oriented Model
This eliminatesrhe useof HOOL and intrcducesthe Object_OrienMmodeldirectly
through
Smalltalk.
Chapter12- Java:An Object-Oriented
Language
Thisis-anentirelynewchaptq,replacingtheSccondEdition'sChapter16on C{_+.It,s approach
is similarto thatof Chapter16.
Chapter13 - The Object-OrientedApproechof Ada 95
This is anentl€ly newchapter.
Chapter14- An Overviewof theDistributedParalletModel
Thischapteris unchargcdfrcm Chapter17of thc SecondEdition.
Chapter15- ConcurrrntUnitsin Ada95
Thischapteris anupdateof Chaptcr18of thc SccondEditionwith modifications
to refl€ctAda
95.
Chapter16 - ConcurrentThrcadsln Java
This is anentirclynewchapter.
Download