Download presentation
Presentation is loading. Please wait.
1
Lecture 4 Java Interfaces (review of inheritance and abstract classes) The XML DOM Java Examples Homework 3
2
Inheritance Review IS-A versus IS-LIKE-A relationship Shape draw() erase() Circle draw() erase() Shape draw() erase() Circle draw() erase() getRadius()
3
void doStuff(Shape s){Shape s.erase(); …Circle Square Some class s.draw(); not yet written } Circle c = new Circle(); doStuff (c) Polymorphism via Dynamic Binding The decision is made at run-time as to which function to call.
4
BankAccount CheckingAccount SavingsAccountSomeOtherAccount Consider
5
public class BankAccount { public void deductFees() { …body… } : } public class SavingsAccount extends BankAccount{ } Writing the BankAccount class But what should we write??
6
Make the class Abstract Better public abstract class BankAccount { public abstract void deductFees(); : } public class SavingsAccount extends BankAccount{ public abstract void deductFees() {…} } No body..It’s up to the derived class to complete. We can write this!
7
Abstract Classes When you extend an existing class, you have a choice whether or not to redefine the methods of the superclass. If you don’t redefine the method, it will appear in the derived class as it appears in the superclass. Sometimes it is desirable to force programmers to redefine a method There may be no good (superclass) default for the method Only the subclass programmer can know how to implement the method
8
Abstract Classes An abstract method has no implementation You can’t construct objects of classes with abstract methods You can only create objects of concrete classes The class must be declared with the keyword abstract It’s fine to have handles that reference abstract classes Abstract classes, unlike interfaces, may have concrete methods and instance variables
9
Another abstract base class public abstract class Shape{ public abstract double area(); public abstract double circumference(); } Require computations only the derived class programmer knows.
10
class Circle extends Shape{ … public double area(){return PI*r*r;} } class Rectangle extends Shape{ } … Shape s = new Rectangle(); System.out.println(s.area()); Another abstract base class
11
Interfaces The interface keyword takes the concept of an abstract class one step further by preventing any function definitions at all!
12
Interfaces 1.The core reason for interfaces is to be able to upcast to more than one base type. C++ multiple inheritance is not supported. 2.Usually better than abstract classes. 3.Allows us to inherit a contract rather than an implementation. 4.When I implement an interface I make a promise that I will provide the required methods.
13
INTERFACES 5. Have no instance variables 6. Have only abstract methods (all parameters but no bodies) 7. Have only public methods 8. Are not classes…you can’t create interface objects 9. May be referenced 10. May contain constants 11. Are implemented not extended as in inheritance
14
INTERFACES Example public interface Comparable { int compareTo(Object other); } public class Student implements Comparable { // this class MUST define compareTo() } Automatically public Is there one correct way to write this?
15
INTERFACES public class Car implements Comparable { // this class MUST define compareTo() }
16
INTERFACES Now, suppose we have a function sort void sort(Comparable x[]) { } Can we pass an array of Student objects to this function? How about an array of Car?
17
INTERFACES void sort(Comparable x[]) { } Can we pass an array of Student objects to this function? Only if Student implements Comparable. How about an array of Car? Only if Car implements Comparable.
18
XML DOM The World Wide Web Consortium’s Document Object Model Provides a common vocabulary to use in manipulating XML documents. May be used from C, Java, Perl, Python, or VB Things may be quite different “under the hood”. The interface to the document will be the same.
19
I am The Cat in The Hat I am Little Cat A I am Little Cat B I am Little Cat C The XML File “cats.xml”
20
Little cat A Little cat B I am little cat B topcat I am the cat in the hat Little cat D Little Cat C I am little cat C I am little cat A document XML doc XML decdoctypeelement textelement text element DOM
21
Agreement.xml 100 5 3 6
22
document XML doc XML decdoctype FixedFloatSwap Notional FixedRate NumYearsNumPayments All of these nodes implement the Node interface
23
Some DOM Documentation from JavaSoft
24
The Node Interface The Node interface is the primary datatype for the entire Document Object Model. It represents a single node in the document tree. While all objects implementing the Node interface expose methods for dealing with children, not all objects implementing the Node interface may have children. For example, Text nodes may not have children.
25
Properties All Nodes have properties. Not all properties are need by all types of nodes. The attribute property is an important part of the Element node but is null for the Text nodes. We access the properties through methods…
26
Some Methods of Node Example Methods are: String getNodeName() – depends on the Node type if Element node return tag name if Text node return #text
27
Some Methods of Node Example Methods are: short getNodeType() Might return a constant like ELEMENT_NODE or TEXT_NODE or …
28
Some Methods of Node Example Methods are: String getNodeValue() if the Node is an Element Node then return ‘null’ if the Node is a Text Node then return a String representing that text.
29
Some Methods of Node Example Methods are: Node getParentNode() returns a reference to the parent
30
Some Methods of Node Example Methods are: public Node getFirstChild() Returns the value of the firstChild property.
31
Some Methods of Node Example Methods are: public NodeList getChildNodes() returns a NodeList object A NodeList object does not implement Node. Why not?
32
The NodeList Interface The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. The items in the NodeList are accessible via an integral index, starting from 0.
33
There are only two methods of the NodeList Interface public Node item(int index) Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
34
There are only two methods of the NodeList Interface public int getLength() Returns the value of the length property.
35
The Element Interface public interface Element extends Node By far the vast majority of objects (apart from text) that authors encounter when traversing a document are Element nodes. Inheritance Nothing prevents us from extending one interface in order to create another.
36
The Element Interface public interface Element extends Node Some methods in the Element interface String getAttribute(String name) Retrieves an attribute value by name.
37
The Element Interface public interface Element extends Node Some methods in the Element interface public String getTagName() Returns the value of the tagName property.
38
The Element Interface public interface Element extends Node Some methods in the Element interface public NodeList getElementsByTagName(String name) Returns a NodeList of all descendant elements with a given tag name, in the order in which they would be encountered in a preorder traversal of the Element tree..
39
The CharacterData Interface public interface CharacterData extends Node The CharacterData interface extends Node with a set of attributes and methods for accessing character data in the DOM. For clarity this set is defined here rather than on each object that uses these attributes and methods. No DOM objects correspond directly to CharacterData, though Text and others do inherit the interface from it. All offsets in this interface start from 0.
40
The CharacterData Interface public interface CharacterData extends Node An example method: public String getData() Returns the value of the the character data of the node that implements this interface. The Text interface extends CharacterData.
41
The Document Interface public interface Document extends Node The Document interface represents the entire HTML or XML document. Conceptually, it is the root of the document tree, and provides the primary access to the document's data.
42
The Document Interface public interface Document extends Node Some methods: public Element getDocumentElement() Returns the value of the documentElement property. This is a convenience attribute that allows direct access to the child node that is the root element of the document. For HTML documents, this is the element with the tagName "HTML".
43
The Document Interface Some methods: public NodeList getElementsByTagName(String tagname) Returns a NodeList of all the Elements with a given tag name in the order in which the would be encountered in a preorder traversal of the Document tree. Parameters: tagname - The name of the tag to match on. The special value "*" matches all tags. Returns: A new NodeList object containing all the matched Elements.
44
An Example import java.io.File; import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException;
45
public class Simulator3 { public static void main(String argv[]) { Document doc; if(argv.length != 1 ) { System.err.println("usage: java Simulator3 documentname"); System.exit(1); } try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
46
doc = docBuilder.parse(new File(argv[0])); Element top = doc.getDocumentElement(); top.normalize(); NodeList elementList = top.getElementsByTagName("*"); int listLength = elementList.getLength(); for(int i = 0; i < listLength; i++) { Element e = (Element)elementList.item(i); System.out.print(e.getNodeName()); Text t = (Text)e.getFirstChild(); System.out.println(t.getNodeValue()); }
47
catch(SAXParseException err) { System.out.println("Parsing error" + ", line " + err.getLineNumber() + ", URI " + err.getSystemId()); System.out.println(" " + err.getMessage()); } catch(SAXException e) { Exception x = e.getException(); ((x == null) ? e : x).printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } System.exit(0); }
48
Agreement.xml 100 5 3 6
49
Output Notional100 Fixed_Rate5 NumYears3 NumPayments6
50
Homework 3 Rewrite the simulator (or modify the one that I wrote) for project 2 so that it reads the SwapAgreement.xml file using Java and the XML DOM
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.