Two Parts of Every ADT - PowerPoint PPT Presentation

1 / 50
About This Presentation
Title:

Two Parts of Every ADT

Description:

Class diagrams include key members, but not ... or not to include a /- key on the ... to include a separate private method, like updateDisplay, or ... – PowerPoint PPT presentation

Number of Views:37
Avg rating:3.0/5.0
Slides: 51
Provided by: maoz4
Category:
Tags: adt | include | parts | two

less

Transcript and Presenter's Notes

Title: Two Parts of Every ADT


1
Abstract Data Type
  • ADT
  • is a type for encapsulating related data
  • is abstract in the sense that it hides
    distracting implementation details

Two Parts of Every ADT
2
Software Development Process
ADT
public class myClass ...
3
Abstract Data Type Example
From the users perspective...
1) What are the operations for this Calculator
ADT?
2) What makes up the state of this ADT?
4
Class Diagram (UML Notation)
5
Class diagrams include key members, but not
usually all members.
Class diagrams show the names of the methods, but
dont fully specify their behavior. Therefore,
we need a ...
6
Class Specification (Partial)
7
public class Calculator private int
displayedOperand, previousOperand private
boolean withinOperand private char lastOp
/ post A new Calculator object is
instantiated and displayedOperand 0
and lastOp and withinOperand /
public Calculator() displayedOperand
0 lastOp withinOperand
true updateDisplay() / post this
display is called to reveal the value of
displayedOperand on the calculator display /
private void updateDisplay() ...
Code
8
/ pre 0 lt d and d lt 9
modifies displayedOperand, withinOperand
post ((withinOperand_at_pre and displayedOperand_at_pr
egt0) implies displayedOperand
displayedOperand_at_pre10 d) and
((withinOperand_at_pre and displayedOperand_at_prelt0)
implies displayedOperand
displayedOperand_at_pre 10 - d) and
(!withinOperand_at_pre implies displayedOperand
d) and withinOperand/ public void
pressDigit( int d ) if (withinOperand)
if (displayedOperand gt 0)
displayedOperand displayedOperand 10
d else displayedOperand
displayedOperand 10 - d
else displayedOperand 0
withinOperand true updateDisplay()
// Additional methods omitted.
9
Design and Implementation
Design determines the softwares architecture
Implementation determines the softwares code
  • Label each decision below as a design or
    implementation.
  • Whether or not to include a /- key on the
    calculator.
  • Whether to use an if or switch instruction within
    the pressDigit method.
  • Whether to use a single pressDigit method and
    parameter or separate methods for each digit.
  • Whether the C button clears both the display
    and previousOperand or clears just the display.
    (Some calculators require two consecutive clears
    to reset everything.)
  • Whether to include a separate private method,
    like updateDisplay, or to include these
    instructions within the necessary methods.
  • Whether to use the given Calculator ADT or a
    different ADT based on GUI objects.
  • Whether to write pressEquals as a void method or
    a double method that returns the result of the
    calculation.

10
Template Patterns, Abstract Classes
and Interfaces
11
Template Design Pattern
  • Sometimes a design technique is used so often
    that it is called a design pattern.
  • Design patterns are generalized approaches that
    apply to a wide variety of situations.
  • This lecture examines the template design pattern
    which involves the use of abstract classes and
    interfaces.

12
Abstract
  • An abstract class is abstract!
  • Captures a property or behavior of an object
    while not defining the implementation.
  • It specifies what a thing does or is
  • Does NOT specify how

13
Abstract Classes
  • Abstract essentially means not completely
    defined
  • Abstract Methods
  • Only the signature is known.
  • modifiers/return type/method name/formal
    parameters/exceptions
  • The method body (implementation) is unknown.
  • Abstract Classes
  • Contain one or more abstract methods.
  • Cannot be instantiated
  • Non-abstract sub-classes must implement all
    abstract methods

14
Abstract Class Example
Problem Write classes to allow the creation of
2D shapes for a paint or draw program.
  • abstract class Shape
  • private double width, height
  • public abstract double getArea()
  • Shape(double w, double h)
  • width w
  • height h
  • public String toString()
  • return " width "," height ,
    getArea()

15
Abstract Class Example
  • class Rectangle extends Shape
  • Rectangle(double w, double h)
  • super(w,h)
  • public double getArea()
  • return width height
  • public String toString()
  • return Rectangle super.toString()

class Oval extends Shape Oval(double w,
double h) super(w,h) public
double getArea() return Math.PI width
height / 4 public String toString()
return Oval super.toString()
16
Abstract Class Example
  • class Demo
  • public static void main(String args)
  • Shape shapes new Shape5
  • // Initialize the elements of the array at
    random
  • for(int i0 iltshapes.length i)
  • int width (int)(Math.random() 30) 1
  • int height (int)(Math.random() 30)
    1
  • // Half of the shapes are ovals and half
    are rectangles
  • // The type of shape is determined at runtime
  • if(Math.random() lt .5)
  • shapesi new Oval(width, height)
  • else
  • shapesi new Rectangle(width,
    height)
  • // Compute and print the total area of all
    shapes in the array
  • double totalArea 0

17
Template Design Pattern
  • The members of a superclass form a template that
    is inherited by all subclasses.
  • Sometimes the primary goal of a class is to serve
    as a template for subclasses (i.e., the template
    defines what subclasses must implement)

The Template Pattern
The true template class forces its subclasses to
implement methods.
abstract classes
interfaces
18
Interfaces
  • An interface is a class containing only
  • abstract methods
  • final variables
  • Essentially a guarantee that any implementing
    class will contain the specified methods.
  • Classes can implement interfaces
  • Represents an is-a relationship (like extending)
  • Can implement multiple interfaces
  • All interface methods must be implemented
  • Adds a multiple inheritance feature to Java

19
Interface Example
Comparable interface codifies the property that
an object can be compared to another! Defined in
java.lang
  • interface Comparable
  • public int compareTo(Object other)
  • // Documentation for the compareTo method
  • Compares this object with the specified other
    object for order. Returns a negative integer,
    zero, or a positive integer as this object is
    less than, equal to, or greater than the
    specified object.
  • Parameters
  • other is the Object to be compared
  • Throws
  • ClassCastException if the specified objects
    type prevents it from being compared to this
    object

20
Interface Example
abstract class Shape implements Comparable
private double width, height public
abstract double getArea() Shape(double w,
double h) width w height h
public String toString() return " width
"," height , getArea()
public int compareTo(Object rhs) Shape other
(Shape)rhs if(getArea() lt other.getArea())
return 1 else if(getArea()
other.getArea()) return 0 else return 1

21
Interface Example
Shape r1 new Rectangle(3, 5) Shape c1 new
Oval(1, 1) if(r1.compareTo(c1) lt 0)
System.out.println(r1 is less than c1)
else if(r1.compareTo(c1) 0) System.out.print
ln(r1 is equal to c1) else
System.out.println(r1 is greater than
c1) if(c1.compareTo(r1) lt 0)
System.out.println(c1 is less than r1)
else if(c1.compareTo(r1) 0) System.out.print
ln(c1 is equal to r1) else
System.out.println(c1 is greater than r1)
22
The Object Class
  • The Object class is an ancestor of all other
    classes.
  • The Object class contains some methods that are
    meant as templates

String toString() provides a textual
description of an object. By default, the
description is the name of the class followed
by _at_ followed by the memory location of the
object.
Example (assuming no over-ride) Oval oval new
Oval(4,1) System.out.println(oval) Oval_at_31c99
Example (assuming over-ride) Oval oval new
Oval(4,1) System.out.println(oval) Oval3,3,3.
1415926
23
The Object Class
  • The Object class is an ancestor of all other
    classes.
  • The Object class contains some methods that are
    meant as templates (equals and toString)

boolean equals(Object other) returns true if
the caller is equal to the called object.
  • Two kinds of equality in Java
  • identity equality compares if two objects are
    the same object (with different names)
  • content equality compares if two different
    objects have the same content (or value)

Examples int x 3 int y 3 Shape s1 new
Rectangle(3,5) Shape s2 new Rectangle(3,5) Sha
pe s3 s1
// consider the following fragments x y s1
s2 s1 s3 s1.equals(s2) s2.equals(s1) s1.equals(
s3)
24
Equals and toString methods
  • Always write a toString and equals method in
    every class (just about)!

abstract class Shape private double width,
height public abstract double getArea()
Shape(double w, double h) width w
height h public String toString()
return " width "," height ,
getArea()
public boolean equals(Object other) if(other
null !(other instanceof Shape)) return
false return ((Shape)other).width width
((Shape)other).height height
class Rectangle extends Shape
Rectangle(double w, double h) super(w,h)
public double getArea() return width
height public String toString()
return Rectangle super.toString()
public boolean equals(Object other) if(other
null) return false return (other instanceof
Rectangle) super.equals(other)
25
Abstract Class vs. Interface
26
Java Collections Framework
27
Java Collections Framework
  • A set of interfaces and classes for storing
    collections of objects
  • A collection is used to store and retrieve data.
  • Collection of Card objects (poker hand)
  • Collection of File objects (a folder)
  • Collection of Book objects (a Library)
  • Collection of Words (a Dictionary)
  • Collection of Songs (a CD)

28
Types of Collections
  • There are three basic kinds of collections
  • Sets
  • Contains elements in no specific order
  • Cannot contain duplicate elements
  • Lists
  • Contains elements in a specific order
  • Also called sequences in our book
  • Can contain duplicate elements
  • Maps
  • Contains elements that are accessed by key
  • when you take CS340

29
Think about it
  • Given the following data, would you store the
    data as a Map, Set, or List?
  • Student data stored by SSN
  • Cards in a poker hand
  • Videos available at a rental store
  • Songs on a CD

30
Java Class Hierarchy
This is the class hierarchy for the built-in
collection classes. Each of the items above is
an interface with multiple implementations.
31
The Collection Interface
  • What methods belong in the Collection class?
  • These methods must make sense in the Map, List,
    and Set classes.
  • The Collection interface is in the java.util
    package

32
Collection Example
33
Problem to IllustrateCollections!!
  • Write a program to read through a text file and
    print to the screen every word that occurs in the
    input file exactly once.

let WordsSeen be an array open file F for every
word W in F if W does not occur in
WordsSeen print W to the terminal add W to
WordsSeen
34
Solution?Wait, this doesnt use collections!
import java.io. import java.util. class
RemoveDuplicateWords private static int
wordCount 0 public static void
main(String args) throws IOException
BufferedReader fin new BufferedReader(new
FileReader(args0)) String words new
String10000 String line while((line
fin.readLine()) ! null) Scanner scan
new Scanner(line) while(scan.hasNext())
String word scan.next()
if(!contains(words, word)) wordswordCount
word fin.close()
for(int i0 iltwordCount i)
System.out.println(wordsi)
public static boolean contains(String words,
String word) for(int i0 iltwordCount i)
if(wordsi.equalsIgnoreCase(word))
return true return false
35
Vectors to the rescue.A Collection!
  • Vectors are
  • a linear collection of data (a List!)
  • similar to arrays but have more power than arrays
  • not arrays!
  • Dynamic. Vectors can grow and shrink as needed
  • There is a Vector class in the java.util package
  • We will examine how to use a Vector
  • We will examine how to implement our own Vector
    class

36
Vector Description(How to use a Vector)
  • add(Object element) appends element to the
    vector
  • boolean contains(Object element) returns true if
    the vector contains object o and false otherwise
  • Object elementAt(int n)returns the Object at
    index n
  • int indexOf(Object element) returns the index
    of the first occurrence of the specified element
  • void insertElementAt(Object element, int n)
    inserts element at n (shifting other elements if
    necessary)
  • Object remove(int n) removes and returns the
    element at index n
  • boolean remove(Object element) removes the
    element if possible. Returns true if removed,
    otherwise false.
  • void setElementAt(Object element, int n)
    overwrites the data at index n. There must
    already be data at index n!
  • int size() returns the number of elements
    stored in the vector
  • int capacity() returns the current capacity of
    the vector

37
Vector Constructors
  • When vectors need to they increase their
    capacity automatically. The capacity increases
    by an amount known as the increment value.
  • Three constructors
  • Vector v new Vector()
  • create an empty vector having the default
    capacity and default increment
  • Vector v new Vector(int capacity)
  • create an empty vector having the specified
    capacity and default increment
  • Vector v new Vector(int capacity, int
    increment)
  • create an empty vector having the specified
    capacity and increment

38
Vector Example(How to use a Vector)
Vector Contents
Output
Method
()
None
Vector v new Vector(4)
()
0
v.size()
()
4
v.capacity()
(A)
None
v.add(A)
(A,B)
None
v.add(B)
(A,B,C)
None
v.add(C)
(A,D,B,C)
None
v.insertElementAt(D, 1)
(A,D,B,C)
C
v.elementAt(3)
(A,D,B,C,E)
None
v.add(E)
(A,D,C,E)
B
v.remove(2)
(F,D,C,E)
None
v.setElementAt(F,0)
(F,D,C,E)
Error
v.setElementAt(G,5)
(D,C,E)
true
v.remove(F)
(D,C,E)
true
v.contains(D)
(D,C,E,C)
None
v.add(C)
(D,C,E,C)
1
v.indexOf(C)
39
Vector syntax
Array String a new String10 ai "Hi,
Mom!" String temp ai
Vector Vector v new Vector() other code that
adds to v v.setElementAt("Hi, Mom!", i) String
temp (String)v.elementAt(i)
40
Arrays versus Vectors
  • Vectors
  • Good
  • Size is not fixed
  • Better storage efficiency a partially full
    vector may be allocated just the space it needs
  • If one more value needs to be added past the
    maximum size the vector size increases
    automatically
  • Bad
  • Less efficient (slower) execution
  • Elements must be class types (primitive types not
    allowed)
  • Arrays
  • Bad
  • Size is fixed when declared
  • Inefficient storage can use a partially full
    array, but space has been allocated for the full
    size
  • If one more value needs to be added past the
    maximum size the array needs to be redeclared
  • Good
  • More efficient (faster) execution
  • Allows primitive type elements

41
Some Gotchas
  • The index given to setElementAt must be between 0
    and the size of the vector minus 1.
  • The index given to insertElementAt must be
    between 0 and the size of the vector.
  • Be sure to understand the difference between
    capacity and size of a vector.
  • capacity is the current maximum number of
    elements
  • the capacity may change during the lifetime of
    the vector
  • size is the actual number of elements stored in
    the vector
  • the size may also change during the lifetime of
    the vector

42
Some Gotchas Class Cast!
  • The following code looks very reasonable but will
    produce an error. Why?
  • Vector v new Vector()
  • String greeting "Hi, Mom!"
  • v.add(greeting)
  • int length v.elementAt(0).length()
  • ALMOST always class cast when using the
    elementAt method.
  • Cast v.elementAt(0) to String
  • int length ((String)v.elementAt(0)).length()

43
Problem
  • Write a program to read through a text file and
    print to the screen every word that occurs in the
    input file exactly once.

let WordsSeen be a Vector open file F for every
word W in F if W does not occur in
WordsSeen print W to the terminal add W to
WordsSeen
44
Solution!
import java.io. import java.util. class
RemoveDuplicateWords public static void
main(String args) throws IOException
BufferedReader fin new BufferedReader(new
FileReader(args0)) Vector words new
Vector() String line while((line
fin.readLine()) ! null) Scanner scan
new Scanner(line) while(scan.hasNext())
String word scan.next()
if(!words.contains(word)) words.add(word)
fin.close() for(int
i0 iltwords.size() i)
System.out.println((String)words.elementAt(i))

45
Vector Pop Quiz!
  • Vector v new Vector()
  • v.add(Hi, Mom)
  • v.add(new Integer(0))
  • v.add(new Double(3.14))
  • v.add(v)
  • System.out.println(((String)v.elementAt(0)).length
    ())
  • System.out.println(((Integer)v.elementAt(1)).intVa
    lue())
  • System.out.println(((Double)v.elementAt(2)).double
    Value())
  • System.out.println(((Vector)v.elementAt(3)).size()
    )

46
Vector Lecture
  • The base type of an array is specified when the
    array is declared
  • The base type is the type of thing contained in
    the array
  • All elements of an array must be of the same type
  • The base type of a vector is Object
  • elements of a vector can be of any class type
    (any Object will do!)
  • to store primitive types in a vector they must be
    converted to a corresponding wrapper class
  • Good Programming Practice
  • Although vectors allow elements in the same
    vector to be of different class types, it is best
    not to have a mix of classes in the same vector.

47
Vector Example
  • Vector v new Vector()
  • for(int i0 ilt10 i)
  • v.add(new Integer(i))
  • // The Vector has 10 elements (numbers 0 through
    9)
  • // Write some code to remove and print the even
    values
  • for(int i0 iltv.size() i2)
  • System.out.println(v.removeElementAt(i))
  • // Does this work?

48
How to Implement a Vector?
  • Write a Vector class
  • How to store the elements that require storage?
  • What instance variables are required?
  • What methods must we write?

class Vector private Object data
private int size public Vector()
public Object elementAt(int i) public int
size() public void setElementAt(int i,
Object o) other methods go here
49
How to Implement a Vector?
  • Write the constructors initialize all instance
    variables!

class Vector protected Object data
protected int size, increment protected
static final int DEFAULT_INCREMENT10,
DEFAULT_CAPACITY10 public Vector(int cap,
int incr) if(cap lt 0 incr lt 0) throw
new IllegalArgumentException() size 0
increment incr data new
Objectcapacity public Vector(int cap)
this(cap, DEFAULT_INCREMENT)
public Vector() this(DEFAULT_CAPACITY,
DEFAULT_INCREMENT) other methods go
here
50
One more time!
import java.io. import java.util. class
RemoveDuplicateWords public static void
main(String args) throws IOException
BufferedReader fin new BufferedReader(new
FileReader(args0)) Vector words new
Vector() String line while((line
fin.readLine()) ! null) Scanner scan
new Scanner(line) while(scan.hasNext())
String word scan.next()
if(!words.contains(word)) words.add(word)
fin.close() for(int
i0 iltwords.size() i)
System.out.println((String)words.elementAt(i))
Write a Comment
User Comments (0)
About PowerShow.com