Upload
jaime-band
View
216
Download
0
Embed Size (px)
Citation preview
ICE1341 ICE1341 Programming LanguagesProgramming Languages
Spring 2005Spring 2005
Lecture #18Lecture #18
In-Young Koiko .AT. icu.ac.kr
Information and Communications University (ICU)
Spring 2005 2 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
AnnouncementsAnnouncements
Makeup class: Makeup class: Wednesday May 18Wednesday May 18thth 4:00PM or 7:00PM4:00PM or 7:00PM????
Handling XML data in a Java programHandling XML data in a Java program W3C Document Object Model W3C Document Object Model ((www.w3.org/DOM/www.w3.org/DOM/))
A simple way to read an XML file in Java A simple way to read an XML file in Java ((www.developerfusion.com/show/2064/www.developerfusion.com/show/2064/))
Working with XML Working with XML ((java.sun.com/xml/jaxp/dist/1.0.1/docs/tutorial/index.htmljava.sun.com/xml/jaxp/dist/1.0.1/docs/tutorial/index.html))
These will be covered in details in the next These will be covered in details in the next classclass
Spring 2005 3 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
DTD (Data Type Definitions)DTD (Data Type Definitions) Final Project AssignmentFinal Project Assignment Chapter 10 – Implementing SubprogramsChapter 10 – Implementing Subprograms
Activation RecordsActivation Records Implementing Subprograms with Stack-Implementing Subprograms with Stack-
Dynamic Local Variables (Dynamic chains)Dynamic Local Variables (Dynamic chains) Implementing Recursive SubprogramsImplementing Recursive Subprograms Implementing Nested Subprograms (Static Implementing Nested Subprograms (Static
chains, Reference to a variable)chains, Reference to a variable)
Last LectureLast Lecture
Spring 2005 4 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
This LectureThis Lecture
Implementing SubprogramsImplementing Subprograms Implementing Program BlocksImplementing Program Blocks Implementing Dynamic ScopingImplementing Dynamic Scoping
Abstraction and EncapsulationAbstraction and Encapsulation Abstract Data TypesAbstract Data Types Encapsulation ConstructsEncapsulation Constructs Naming EncapsulationsNaming Encapsulations
Spring 2005 5 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Static Chains to Access VariablesStatic Chains to Access Variablesprogram program Main_2Main_2;; var X : integer;var X : integer; procedure procedure BigsubBigsub;; var A, B, C : integer;var A, B, C : integer; procedure procedure Sub1Sub1;; var A, D : integer;var A, D : integer; beginbegin A := B + C;A := B + C; end;end; procedure procedure Sub2Sub2(X : integer);(X : integer); var B, E : integer;var B, E : integer; procedure procedure Sub3Sub3;; var C, E : integer;var C, E : integer; beginbegin Sub1;Sub1; E := B + A:E := B + A: end;end; beginbegin Sub3;Sub3; A := D + E;A := D + E; end;end; beginbegin Sub2(7);Sub2(7); end;end; beginbegin Bigsub;Bigsub; end.end. Ada
References to References to the variable Athe variable A
(0, 3)(0, 3)
(2, 3)(2, 3)
(1, 3)(1, 3)
Spring 2005 6 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Evaluation of the Static Chain MethodEvaluation of the Static Chain Method
A nonlocal reference is A nonlocal reference is slowslow if the number of if the number of scopes between the reference and the scopes between the reference and the declaration of the referenced variable is largedeclaration of the referenced variable is large
Time-critical code is difficult, because the costs Time-critical code is difficult, because the costs of of nonlocal references are not equalnonlocal references are not equal, and can , and can change with code upgrades and fixeschange with code upgrades and fixes
DisplayDisplay: An alternative to static chains. An : An alternative to static chains. An array of static linksarray of static links ( (addresses of accessible addresses of accessible activation record instancesactivation record instances). ).
Spring 2005 7 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Program BlocksProgram Blocks
2. Allocate locals 2. Allocate locals on top of the on top of the activation activation record instancerecord instance Must use a Must use a
different different method to method to access localsaccess locals
void main () {void main () {int x, y, z;int x, y, z;while ( … ) {while ( … ) { int a, b, c;int a, b, c; … … while ( … ) {while ( … ) {
int d, e;int d, e; … …
}}}}while ( … ) {while ( … ) { int f, g;int f, g; … …}}……
}}
1. Treat blocks as 1. Treat blocks as parameterless subprogramsparameterless subprograms
Spring 2005 8 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Implementing Dynamic Scoping (1)Implementing Dynamic Scoping (1)
void sub3() {void sub3() {int int xx, , zz;;x = u + v;x = u + v;……
}}void sub2() {void sub2() {
int int ww, , xx;;……
}}void sub1() {void sub1() {
int int vv, , ww;;……
}}void main() {void main() {
int int vv, , uu;;……
}}11
22
44
33
Deep AccessDeep Access: Nonlocal : Nonlocal references are found by references are found by searching the activation searching the activation record instances on the record instances on the dynamic chaindynamic chain
Length of chainLength of chain cannot be statically cannot be statically determined at determined at compile timecompile time
Slower executionSlower execution Every activation Every activation
record instance must record instance must have have variable namesvariable names
* AW Lecture Notes
Spring 2005 9 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Implementing Dynamic Scoping (2)Implementing Dynamic Scoping (2)
void sub3() {void sub3() {int int xx, , zz;;x = u + v;x = u + v;……
}}void sub2() {void sub2() {
int int ww, , xx;;……
}}void sub1() {void sub1() {
int int vv, , ww;;……
}}Void main() {Void main() {
int int vv, , uu;;……
}}
Shallow AccessShallow Access One stack for eachOne stack for each variable name variable name
Central tableCentral table that has a that has a locationlocation and an and an ““active bitactive bit” for each different variable ” for each different variable name in a programname in a program
e.g., COBOLe.g., COBOL* AW Lecture Notes
11
22
44
33
2
1
2
2
sub3
Spring 2005 10
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Chapter 11Chapter 11Abstraction and Abstraction and EncapsulationEncapsulation
Spring 2005 11
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
AbstractionAbstraction
Extraction of Extraction of essential characteristicsessential characteristics (data (data fields and functions) of an objectfields and functions) of an object
Not including unimportant details of an objectNot including unimportant details of an object
FriendFriend- name : String- name : String- email : String- email : String- phone: String- phone: String
<<constructor>><<constructor>> Friend(name: String) Friend(name: String)+ getName() : String+ getName() : String+ setName(name: String)+ setName(name: String)……
An abstraction of the real-world objectAn abstraction of the real-world object
Spring 2005 12
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Abstraction Abstraction – cont.– cont.
AbstractionAbstraction: A view or representation of an : A view or representation of an entity that includes entity that includes only the attributes of only the attributes of significancesignificance in a particular context in a particular context Implementation details are hiddenImplementation details are hidden from users from users Simplify programming processSimplify programming process Types: Types: Data AbstractionData Abstraction, , Process AbstractionProcess Abstraction
StackStack
PushPush PopPop
TopTop
Data structureData structure – a list that grows and – a list that grows and shrinks at one end onlyshrinks at one end only
OperationsOperations – – push(stk1, ele), pop(stk1), push(stk1, ele), pop(stk1), top(stk1), create(stk1), destroy(stk1)top(stk1), create(stk1), destroy(stk1)
Spring 2005 13
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Abstract Data TypesAbstract Data Types Abstract Data TypeAbstract Data Type: A user-defined data type : A user-defined data type
that satisfies the following two conditions:that satisfies the following two conditions: The The representationrepresentation of, and of, and operationsoperations on, on, objectsobjects of of
the type are defined in a the type are defined in a single syntactic unitsingle syntactic unit
e.g., e.g., Stack stk1, stk2; create(stk1); create(stk2); …Stack stk1, stk2; create(stk1); create(stk2); …
push(stk1, color1); color2 = pop(stk2);push(stk1, color1); color2 = pop(stk2);
The The representation of objects of the type is hiddenrepresentation of objects of the type is hidden from the program units that use these objects, so the from the program units that use these objects, so the only operations possible are those providedonly operations possible are those provided in the in the type's definitiontype's definition
Clients of a Data TypeClients of a Data Type: Program units that use : Program units that use a specific abstract data typea specific abstract data type
Spring 2005 14
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
An Example of Abstract Data TypesAn Example of Abstract Data Types
class class StackStack extends Vector { extends Vector {public public Stack()Stack() { // create{ // create
super();super(); }}
public public Object push(Object item)Object push(Object item) { {addElement(item);addElement(item);
}}public public Object pop()Object pop() {{
int top = size() – 1;int top = size() – 1;if (top < 0) return null;if (top < 0) return null;elseelse return elementAt(top);return elementAt(top);
}}……
} // } // Implementation of the stackImplementation of the stack //// data type in Java using a data type in Java using a VectorVector Change to use a Change to use a
Linked ListLinked List
The client doesn’t The client doesn’t need to be changedneed to be changed
A ClientA Client
StackStack stk1 = stk1 =new new Stack()Stack();;
stk1.stk1.pushpush(“1st ele”);(“1st ele”);stk1.stk1.pushpush( “2nd ele”);( “2nd ele”);……String ele =String ele = (String)stk1.(String)stk1.poppop();();
Spring 2005 15
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Design Issues for Abstract Data TypesDesign Issues for Abstract Data Types
EncapsulationEncapsulation: A syntactic unit in which to : A syntactic unit in which to encapsulate the encapsulate the type definitiontype definition
Information HidingInformation Hiding: A method of : A method of making type making type names and subprogram headers visible to names and subprogram headers visible to clientsclients, while hiding actual definitions, while hiding actual definitions
Some Some primitive operationsprimitive operations must be built into the must be built into the language processor (usually just language processor (usually just assignmentassignment and and comparisonscomparisons for equality and inequality) for equality and inequality) Some operations are commonly needed, but must be Some operations are commonly needed, but must be
defined by the type designerdefined by the type designer
e.g., e.g., iterators, constructors, destructorsiterators, constructors, destructors* AW Lecture Notes
Spring 2005 16
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Abstract Data Types in AdaAbstract Data Types in Ada
EncapsulationEncapsulation construct: ‘construct: ‘packagepackage’’
Information hidingInformation hiding via via the ‘the ‘privateprivate’ part’ part
Specification PackageSpecification Package: : an an interface of an interface of an encapsulationencapsulation (visible (visible to clients)to clients)
Body PackageBody Package: : implementation implementation (hidden from clients)(hidden from clients)
A A client client of the package of the package Linked_List_TypeLinked_List_Type
packagepackage Linked_List_Type is Linked_List_Type istype type Node_TypeNode_Type is private; is private;……privateprivate type Node_Type;type Node_Type; type Ptr is access Node_Type;type Ptr is access Node_Type; type Node_Type istype Node_Type is
recordrecord Info : Integer;Info : Integer; Link : Ptr;Link : Ptr;end record;end record;
end Linked_List_Type;end Linked_List_Type;……useuse Linked_List_Type; Linked_List_Type;procedureprocedure Use_Linked_Lists Use_Linked_Lists isis
Node : Node : Node_TypeNode_Type;;
Spring 2005 17
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Abstract Data Types in C++Abstract Data Types in C++ Data MembersData Members ConstructorConstructor
InitializesInitializes the data members the data members Implicitly calledImplicitly called when an instance is when an instance is
created (Can be explicitly called)created (Can be explicitly called) Name is the same as the class nameName is the same as the class name
DestructorDestructor CleanupCleanup after an instance is after an instance is
destroyed (e.g., free heap storage)destroyed (e.g., free heap storage) Implicitly calledImplicitly called when the object’s when the object’s
lifetime ends (Can be explicitly called)lifetime ends (Can be explicitly called) Name is the class name, preceded by Name is the class name, preceded by
a tilde (~)a tilde (~)
Member FunctionsMember Functions
class stack {class stack {private: int private: int *ptr, max, top*ptr, max, top;;public: public: stack()stack() { { ptr = new int [100];ptr = new int [100]; max = 99;max = 99; top = -1;top = -1;}}~stack()~stack() { delete [] ptr; }; { delete [] ptr; };void push(int num)void push(int num) { { if (top < max)if (top < max)
ptr[++top] = num;ptr[++top] = num;}}……
}}
Spring 2005 18
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Abstract Data Types in C++Abstract Data Types in C++
EncapsulationEncapsulation by by classesclasses Each instance of a class has its Each instance of a class has its
own copy of own copy of data membersdata members Class instances share a single copy Class instances share a single copy
of the of the member functionsmember functions Instances can be static, stack Instances can be static, stack
dynamic, or heap dynamicdynamic, or heap dynamic
Information HidingInformation Hiding PrivatePrivate clause clause for hidden entities for hidden entities PublicPublic clause clause for interface entities for interface entities
Client partClient partCreates an instanceCreates an instance
Access a member functionAccess a member function
classclass stackstack { {privateprivate: int *ptr, max, top;: int *ptr, max, top;publicpublic: : stack()stack() { { ptr = new int [100];ptr = new int [100]; max = 99;max = 99; top = -1;top = -1;}}~stack()~stack() { delete [] ptr; }; { delete [] ptr; };void push(int num)void push(int num) { { if (top < max)if (top < max)
ptr[++top] = num;ptr[++top] = num;}}……
}}void main() {void main() {
stack stk;stack stk;stk.push(42); …stk.push(42); …
Spring 2005 19
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Abstract Data Types in C#Abstract Data Types in C#
Accessor methodsAccessor methods ((gettersgetters and and setterssetters): ): allow indirect access allow indirect access to hidden data to hidden data membersmembers
C# provides C# provides propertiesproperties as a way as a way of implementing of implementing getters and setters getters and setters without requiring without requiring explicit method callsexplicit method calls
public class public class WeatherWeather { {public int public int DegreeDaysDegreeDays { { getget { {
return degreeDays;return degreeDays; } } setset { {
degreeDays = value;degreeDays = value; }}}}private int degreeDays;private int degreeDays;......
}}......Weather w = new Weather();Weather w = new Weather();int todaysDegree, oldDegree; …int todaysDegree, oldDegree; …w.DegreeDays = todaysDegree;w.DegreeDays = todaysDegree;oldDegree = w.DegreeDays;oldDegree = w.DegreeDays;
Spring 2005 20
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Parameterized Abstract Data TypesParameterized Abstract Data Types
Making the stack class Making the stack class usable for usable for any data any data typetype and and arbitrary arbitrary maximum sizemaximum size
Making the class a Making the class a templated classtemplated class
Using Using parameterized parameterized constructorconstructor functions functions
templatetemplate <class <class TypeType>>class stack {class stack {
private: int *ptr, max, top;private: int *ptr, max, top;public: stack(int public: stack(int sizesize) {) { ptr = new ptr = new TypeType [ [sizesize];]; max = max = sizesize - 1; - 1; top = -1;top = -1;}}~stack() { delete [] ptr; };~stack() { delete [] ptr; };void push(int num) {void push(int num) { if (top < max)if (top < max)
ptr[++top] = num;ptr[++top] = num;}}……
}}C++
Spring 2005 21
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Encapsulation & Information HidingEncapsulation & Information Hiding In Java or C++, both In Java or C++, both data membersdata members and and member functionsmember functions
are defined in a classare defined in a class An An interfaceinterface hides the implementation detailshides the implementation details of data of data
structures and functions of an objectstructures and functions of an object Information hidingInformation hiding ensures the ensures the data integritydata integrity by preventing by preventing
programmers from accessing data incorrectlyprogrammers from accessing data incorrectly
FriendFriend
<<constructor>><<constructor>> Friend(name: String) Friend(name: String)+ getName() : String+ getName() : String+ setName(name: String)+ setName(name: String)+ getEmail() : String+ getEmail() : String+ setEmail(email: String)+ setEmail(email: String)……
An interface to access the objectAn interface to access the object
public class public class FriendFriend { {private String name, email, phone;private String name, email, phone;public public FriendFriend ( String name ) { ( String name ) {
this.name = name;this.name = name;}}public String getName() {public String getName() {
return name;return name;}}public viod setName(String name) {public viod setName(String name) {
this.name = name;this.name = name;}}……
}}
Spring 2005 22
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Encapsulation ConstructsEncapsulation Constructs
Motivation – Large programs with thousands of Motivation – Large programs with thousands of lines have two special needs:lines have two special needs:1. Some 1. Some means of organizationmeans of organization to keep them to keep them
intellectually manageableintellectually manageable
2. Some 2. Some means of partial compilationmeans of partial compilation (compilation (compilation units that are smaller than the whole program)units that are smaller than the whole program)
Solution – Solution – EncapsulationEncapsulation: a : a grouping of grouping of subprogramssubprograms that are logically related into a that are logically related into a unit that can be separately compiled unit that can be separately compiled ((compilation unitscompilation units))
e.g., Java e.g., Java packagespackages, C library & , C library & header filesheader files* AW Lecture Notes
Spring 2005 23
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Java PackagesJava Packages
Spring 2005 24
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Naming Encapsulations (1)Naming Encapsulations (1)
Large programs define Large programs define many global namesmany global names; ; need need a way to divide into logical groupingsa way to divide into logical groupings
A A naming encapsulationnaming encapsulation is used to create a is used to create a new scope for namesnew scope for names
C++, C# C++, C# NamespacesNamespaces – One can place each – One can place each library in its own namespace and qualify names library in its own namespace and qualify names used outside with the namespaceused outside with the namespace
namespace Stack1 {namespace Stack1 { namespace Stack2 namespace Stack2 {{
int top; …int top; … int top; … int top; …}} }}Stack1::top = Stack2::top;Stack1::top = Stack2::top; * AW Lecture Notes
Spring 2005 25
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Naming Encapsulations (2)Naming Encapsulations (2)
Java Java PackagesPackages Packages can contain Packages can contain more than one class more than one class
definitiondefinition; classes in a package are ; classes in a package are partial friendspartial friends Clients use fully qualified names (e.g., Clients use fully qualified names (e.g., java.io.Filejava.io.File) or ) or
use the ‘use the ‘importimport’ declaration (e.g., ’ declaration (e.g., import java.io.*;import java.io.*;)) Ada Ada PackagesPackages
Packages are defined in hierarchies which Packages are defined in hierarchies which correspond to file hierarchiescorrespond to file hierarchies
VisibilityVisibility from a program unit is gained with the ‘ from a program unit is gained with the ‘withwith’ ’ clause (e.g., clause (e.g., with Ada.Text_IO;with Ada.Text_IO;))
To To access names without qualificationaccess names without qualification, the ‘, the ‘useuse’ ’ clause can be used (e.g., clause can be used (e.g., use Ada.Text_IOuse Ada.Text_IO))
* AW Lecture Notes