Post on 02-Jan-2016
transcript
April 30, 2004 1 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Programming LanguagesProgramming Languages(ICE 1341)(ICE 1341)
Lecture #18Lecture #18 April 30, 2004
In-Young Koiko .AT. icu.ac.kr
Information and Communications University (ICU)
April 30, 2004 2 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Review of the Previous LecturesReview of the Previous Lectures
The Concept of AbstractionThe Concept of Abstraction Abstract Data TypesAbstract Data Types Design Issues for Abstract Data TypesDesign Issues for Abstract Data Types
Encapsulation MechanismsEncapsulation Mechanisms Support for Information HidingSupport for Information Hiding Primitive OperationsPrimitive Operations
Parameterized Abstract Data TypesParameterized Abstract Data Types Encapsulation ConstructsEncapsulation Constructs Naming EncapsulationsNaming Encapsulations
April 30, 2004 3 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Software ReuseSoftware Reuse
How can we increase How can we increase software productivitysoftware productivity?? By improving By improving software reusabilitysoftware reusability
How can we improve software reusability?How can we improve software reusability? By supporting By supporting abstractionabstraction mechanisms mechanisms Abstract data types (ADTs)Abstract data types (ADTs) are the units to be are the units to be reusedreused
What are the problems with using ADTsWhat are the problems with using ADTs Needs Needs minor modificationsminor modifications (on both the data type and (on both the data type and
clients) for a new useclients) for a new use Needs a mechanism to Needs a mechanism to relate similar ADTsrelate similar ADTs that are that are
generated from one ADTgenerated from one ADT Any solutions? Any solutions? Inheritance mechanismInheritance mechanism
April 30, 2004 4 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Examples of Examples of InheritanceInheritance
ListList
addadd(int, Object), (int, Object), getget(int): Object(int): Objectremoveremove(int), (int), clearclear()()sizesize(): int, (): int, containscontains(Object): boolean(Object): boolean
Linked ListLinked List
addadd(int, Object), (int, Object), getget(int): Object(int): Objectremoveremove(int), (int), clearclear()()sizesize(): int, (): int, containscontains(Object): boolean(Object): booleanaddFirstaddFirst(Object), (Object), addLastaddLast(Object)(Object)getFirstgetFirst(): Object, (): Object, getLastgetLast(): Object(): ObjectremoveFirstremoveFirst(), (), removeLastremoveLast()()
VectorVector
addadd(int, Object), (int, Object), getget(int): Object(int): Objectremoveremove(int), (int), clearclear()()sizesize(): int, (): int, containscontains(Object): boolean(Object): booleancapacitycapacity(): int, (): int, setSizesetSize(int)(int)
StackStack
emptyempty(): boolean, (): boolean, toptop(): Object(): Objectpushpush(Object), (Object), poppop(): Object(): Object
April 30, 2004 5 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Object-Oriented Programming (OOP)Object-Oriented Programming (OOP)
A programming paradigm that centers around A programming paradigm that centers around ““objectsobjects,” which are ,” which are similar to real-world objectssimilar to real-world objects
Programmers see the execution of Programmers see the execution of a program a program as a collection of as a collection of dialoguing objectsdialoguing objects [Wikipedia] [Wikipedia]
OOP languages (OOPL) began in OOP languages (OOPL) began in 1960s1960s with with the the SimularSimular project, which project, which incorporated the incorporated the notions of notions of objects and inheritanceobjects and inheritance
OOPLs: Smalltalk, Ada 95, CLOS, Scheme, OOPLs: Smalltalk, Ada 95, CLOS, Scheme, Eiffel, C++, JavaEiffel, C++, Java
April 30, 2004 6 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
OOP DefinitionsOOP Definitions
CClasseslasses: Abstract data types: Abstract data types OObjectsbjects: Instances of a class: Instances of a class Subclass (Derived Class)Subclass (Derived Class): : A class that inherits A class that inherits
another classanother class SSuperclass uperclass (P(Parent arent CClasslass)):: The class from The class from
which another classwhich another classeses inherit inherit MethodsMethods: : Subprograms that define operations Subprograms that define operations
on objectson objects MMessagesessages: : Calls to methodsCalls to methods (Destination object (Destination object
+ Method name)+ Method name) MMessage essage PProtocol rotocol (M(Message essage IInterfacenterface)): : The The
entire collection of methods of an objectentire collection of methods of an object
April 30, 2004 7 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Access Control and Overriden MethodsAccess Control and Overriden Methods
Inheritance can be complicated by Inheritance can be complicated by access access controlscontrols to encapsulated entities to encapsulated entities A class can A class can hide entities from its subclasseshide entities from its subclasses A class can A class can hide entities from its clientshide entities from its clients A class can also hide entities frA class can also hide entities fromom its clients while its clients while
allowing its subclasses to see themallowing its subclasses to see them ( (ProtectedProtected))
Besides inheriting methods as is, a class can Besides inheriting methods as is, a class can modify an inherited methodmodify an inherited method The new one The new one overridesoverrides the inherited one the inherited one The method in the parent is The method in the parent is overridenoverriden
* AW Lecture Notes
April 30, 2004 8 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Examples of Examples of Overriden MethodsOverriden Methods
ListList
addadd(int, Object), (int, Object), getget(int): Object(int): Objectremoveremove(int), (int), clearclear()()sizesize(): int, (): int, containscontains(Object): boolean(Object): boolean
Linked ListLinked List
addadd(int, Object), (int, Object), getget(int): Object(int): Objectremoveremove(int), (int), clearclear()()sizesize(): int, (): int, containscontains(Object): boolean(Object): booleanaddFirstaddFirst(Object), (Object), addLastaddLast(Object)(Object)getFirstgetFirst(): Object, (): Object, getLastgetLast(): Object(): ObjectremoveFirstremoveFirst(), (), removeLastremoveLast()()
VectorVector
addadd(int, Object), (int, Object), getget(int): Object(int): Objectremoveremove(int), (int), clearclear()()sizesize(): int, (): int, containscontains(Object): boolean(Object): booleancapacitycapacity(): int, (): int, setSizesetSize(int)(int)
StackStack
emptyempty(): boolean, (): boolean, toptop(): Object(): Objectpushpush(Object), (Object), poppop(): Object(): Object
Methods that override Methods that override the ones in Listthe ones in List
April 30, 2004 9 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Kinds of Methods and VariablesKinds of Methods and Variables
There are two kinds of variables in a class:There are two kinds of variables in a class: Class variablesClass variables – belong to a class (e.g., – belong to a class (e.g.,
static variables in Javastatic variables in Java)) Instance variablesInstance variables – belong to an instance– belong to an instance
There are two kinds of methods in a class:There are two kinds of methods in a class: Class methodsClass methods – accept messages to the – accept messages to the
classclass (e.g., (e.g., static methods in Javastatic methods in Java)) Instance methodsInstance methods – accept messages to – accept messages to
objectsobjects
* AW Lecture Notes
April 30, 2004 10 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Abstract Classes and MethodsAbstract Classes and Methods
Abstract methodAbstract method: : one that does not one that does not include a definition include a definition (it only defines a (it only defines a protocol)protocol)
Abstract classAbstract class is is one that includes at one that includes at least one virtual least one virtual methodmethod
An abstract class An abstract class cannot be cannot be instantiatedinstantiated
public public interfaceinterface ListList { {public boolean add(Object);public boolean add(Object);public boolean remove(Object);public boolean remove(Object);public int size();public int size();public void clear();public void clear();……
}}public public abstract classabstract class AbstractListAbstractList
implements List {implements List {……// Partial implementation of List// Partial implementation of List……
}}public public classclass VectorVector extends extends
AbstractList {AbstractList {……
}} Java
April 30, 2004 11 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Design Issues for OOPL (1)Design Issues for OOPL (1)
The Exclusivity of ObjectsThe Exclusivity of Objects Everything is an objectEverything is an object - - EElegancelegance and and uniformityuniformity, but , but
slow operations on simple objectsslow operations on simple objects (e.g., float) (e.g., float) Add objects to a complete typing systemAdd objects to a complete typing system – F – Fastast
operations on simple objectsoperations on simple objects, but , but results in a results in a confusing type systemconfusing type system (two kinds of entities (two kinds of entities, e.g., , e.g., IntegerInteger and and intint in Java in Java))
Are Subclasses Subtypes?Are Subclasses Subtypes? Does an “Does an “is-a” relationshipis-a” relationship hold between a parent hold between a parent
class object and an object of the subclass?class object and an object of the subclass? e.g., Ada – e.g., Ada – subtype Small_Int is Integer range 0..100;subtype Small_Int is Integer range 0..100;
* AW Lecture Notes
April 30, 2004 12 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Design Issues for OOPL (2)Design Issues for OOPL (2)
Type Checking and PolymorphismType Checking and Polymorphism PolymorphismPolymorphism may may requirerequire
dynamic type checkingdynamic type checking of of parameters and the return valueparameters and the return value
Dynamic type checking is Dynamic type checking is costly costly and delays error detectionand delays error detection
If overriding methods are If overriding methods are restricted to having the same restricted to having the same parameter types and return typeparameter types and return type, , the checking can be staticthe checking can be static
e.g., e.g., IntVector v = new IntVector();IntVector v = new IntVector();v.add(new Integer(20));v.add(new Integer(20));
class Vector {class Vector {void void add(Object item)add(Object item) { {
……} …} …
}}class IntegerVector class IntegerVector
extends Vector {extends Vector {void void add(Integer item)add(Integer item) { {
……} …} …
}}class IntVector extends class IntVector extends
IntegerVector {IntegerVector {void void add(int item)add(int item) { {
……} …} …
}} * AW Lecture Notes
April 30, 2004 13 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Design Issues for OOPL (3)Design Issues for OOPL (3)
Single Single vs.vs. Multiple Inheritance Multiple Inheritance Disadvantages of multiple inheritanceDisadvantages of multiple inheritance::
Language and implementation Language and implementation complexitycomplexity (in (in part due to part due to name collisionsname collisions))
Potential Potential inefficiencyinefficiency - - dynamic binding costs dynamic binding costs moremore with multiple inheritance with multiple inheritance
Allocation and Deallocation of ObjectsAllocation and Deallocation of Objects From where From where are objects allocated?are objects allocated? – In the – In the heap or heap or
stackstack area? area? Is deallocation Is deallocation explicit or implicitexplicit or implicit?? – e.g., Garbage – e.g., Garbage
collectorscollectors* AW Lecture Notes
April 30, 2004 14 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Object-Oriented Processing of Object-Oriented Processing of XML DataXML Data
April 30, 2004 15 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
XML ProcessorsXML Processors
XML XML DocumentDocument
DatabasesDatabases
XML ParserXML Parser
DTD/ DTD/ XMLSchemaXMLSchema
XSL XSL DescriptionDescription
XSL ProcessorXSL Processor
XML Grammar XML Grammar (Structure) Validation(Structure) Validation
DOM ObjectsDOM Objects
HTML HTML PresentationPresentation
classclass
namename codecode studentsstudents
ProgProg. Lang. Lang ICE1341ICE1341 studentstudent studentstudent
namename bdaybday namename bdaybday
Y.K. KoY.K. Ko 820304820304 D.W. KimD.W. Kim 830512830512
classclass
namename codecode studentsstudents
ProgProg. Lang. Lang ICE1341ICE1341 studentstudent studentstudent
namename bdaybday namename bdaybday
Y.K. KoY.K. Ko 820304820304 D.W. KimD.W. Kim 830512830512
Parsing EventsParsing Events
DOM APIDOM API SAX APISAX API
April 30, 2004 16 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
XML APIsXML APIs
SAX (Simple API for XML)SAX (Simple API for XML) – – XML-DEVXML-DEV Stream-based Access InterfaceStream-based Access Interface (Sequential Access) (Sequential Access) Notifies an application of a stream of Notifies an application of a stream of parsing eventsparsing events Needs a Needs a Content HandlerContent Handler to handle the parsing to handle the parsing
events (e.g., start and end of an element)events (e.g., start and end of an element) Appropriate to handle a large XML document Appropriate to handle a large XML document
DOM (Document Object Model)DOM (Document Object Model) – – W3CW3C Object-oriented Access Interface Object-oriented Access Interface (Random Access)(Random Access) Builds a Builds a tree of nodestree of nodes based on the structure and based on the structure and
information in an XML documentinformation in an XML document Types of nodes: Types of nodes: DocumentDocument, , ElementElement, , AttrAttr, …, …
April 30, 2004 17 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
DOM RepresentationDOM Representation
classclass
namename codecode studentsstudents
ProgProg. Lang. Lang ICE1341ICE1341 studentstudent studentstudent
namename bdaybday namename bdaybday
Y.K. KoY.K. Ko 820304820304 D.W. KimD.W. Kim 830512830512
classclass
namename codecode studentsstudents
ProgProg. Lang. Lang ICE1341ICE1341 studentstudent studentstudent
namename bdaybday namename bdaybday
Y.K. KoY.K. Ko 820304820304 D.W. KimD.W. Kim 830512830512
<class><class> <name><name>Prog. Lang.Prog. Lang.</name></name> <code><code>ICE1341ICE1341</code></code> <students><students>
<student <student id=“20037001”id=“20037001”>> <name><name>Y.K. KoY.K. Ko</name></name> <bday><bday>820304820304</bday></bday> </student></student> <student <student id=“20037002”id=“20037002”>> <name><name>D.W. KimD.W. Kim</name></name> <bday><bday>830512830512</bday></bday> </student></student>
</students></students></class></class>
XML DocumentXML Document DOM RepresentationDOM Representation
Document Document (Root Node)(Root Node)
Elements Elements (Child Nodes)(Child Nodes)
Node Values Node Values (Text Nodes)(Text Nodes)
April 30, 2004 18 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Java API Hierarchy for DOMJava API Hierarchy for DOM
NodeNode
getChildNodesgetChildNodes(): NodeList(): NodeListgetAttributesgetAttributes(): NamedNodeMap(): NamedNodeMapgetNodeNamegetNodeName(): String(): StringgetNodeValuegetNodeValue(): String(): StringappendChildappendChild(Node)(Node)removeChildremoveChild(Node)(Node)setNodeValuesetNodeValue(String)(String)
AttrAttr
getNamegetName(): String(): StringgetValuegetValue(): String(): StringsetValuesetValue(String)(String)
CharacterDataCharacterData
getDatagetData(): String(): StringgetLengthgetLength(): int(): intsetDatasetData(String)(String)
DocumentDocument
createAttributecreateAttribute(String): Attr(String): AttrcreateElementcreateElement(String): Element(String): ElementcreateTextNodecreateTextNode(String): Text(String): TextgetDocumentElementgetDocumentElement(): Element(): ElementgetElementByTagNamegetElementByTagName(String): NodeList(String): NodeList
ElementElement
getAttributegetAttribute(String): String(String): StringgetTagNamegetTagName(): String(): String
TextText
splitTextsplitText(int): Text(int): Text
CommentComment
April 30, 2004 19 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
An Example of Creating DOM Objects An Example of Creating DOM Objects from an XML Filefrom an XML File
try {try { DocumentBuilderFactoryDocumentBuilderFactory docBuilderFactory = docBuilderFactory =
DocumentBuilderFactory.DocumentBuilderFactory.newInstancenewInstance();(); DocumentBuilderDocumentBuilder docBuilder docBuilder = = docBuilderFactory.docBuilderFactory.newDocumentBuildernewDocumentBuilder();(); DocumentDocument doc = doc =
docBuilder.docBuilder.parseparse(new File("(new File("sample.xmlsample.xml"));")); ElementElement rootEle = rootEle = doc.doc.getDocumentElementgetDocumentElement()();; NodeListNodeList children = rootEle. children = rootEle.getChildNodesgetChildNodes();(); for (int i = 0; i < children.for (int i = 0; i < children.getLengthgetLength(); i++) {(); i++) { NodeNode subEle = children. subEle = children.itemitem(i);(i); … … }}} catch(Exception e) { e.printStackTrace();} catch(Exception e) { e.printStackTrace(); }}
April 30, 2004 20 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Related MaterialsRelated Materials
W3C Document Object ModelW3C 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))
Java Technology and XML FAQs Java Technology and XML FAQs ((java.sun.com/xml/faq.htmljava.sun.com/xml/faq.html))
Java API Manual Java API Manual ((java.sun.com/j2se/1.4.2/docs/api/java.sun.com/j2se/1.4.2/docs/api/))
See See org.w3c.domorg.w3c.dom and and javax.xml.parsersjavax.xml.parsers XML.org XML.org ((www.xml.orgwww.xml.org))
April 30, 2004 21 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Final Project – Implementing a Cross Final Project – Implementing a Cross Compiler for the XML-based LanguageCompiler for the XML-based Language
1.1. Use Java’s DOM API to read your sample Use Java’s DOM API to read your sample programprogram written in your XML-based written in your XML-based programming languageprogramming language
2.2. Traverse through the nodes in the DOM Traverse through the nodes in the DOM representation of your sample program, and representation of your sample program, and convert them into another structured convert them into another structured programming languageprogramming language (e.g., Java, C, C++) (e.g., Java, C, C++)
3.3. Compile the resulting programCompile the resulting program with a compiler with a compiler for the target languagefor the target language
4.4. Run the programRun the program to validate that the program to validate that the program has been converted correctlyhas been converted correctly
April 30, 2004 22 ICE 1341 – Programming Languages (Lecture #18) In-Young Ko
Final Project – Report & PresentationFinal Project – Report & Presentation
Please submit a report that includes the following Please submit a report that includes the following by by May 28, 2004May 28, 2004 The The input XML programinput XML program (with more than 50 lines) (with more than 50 lines) The The resulting programresulting program in another language in another language Textual description about your Textual description about your cross compiler designcross compiler design Java source codeJava source code of your cross compiler of your cross compiler DiscussionsDiscussions
Explain about the language design decisions that made it easy Explain about the language design decisions that made it easy and efficient to implement the cross compiler and efficient to implement the cross compiler
Explain about the language design decisions that made it Explain about the language design decisions that made it difficult to implement the cross compilerdifficult to implement the cross compiler
Present your language and compiler designs at Present your language and compiler designs at the classes during the classes during the week of May 28ththe week of May 28th