Upload
alaina-lawrence
View
216
Download
0
Embed Size (px)
Citation preview
1
Review for the AP CS Exam
Object Oriented Program Design– Program Design
• Read and Understand class specifications and relationships among the classes(has a and is a relationships)
• Decompose a problem into classes, define relationships and responsibilities of those classes
2
– Top down approach• Make a list of all of the things that a program must
accomplish• Each of those things becomes its own module
(perhaps a method or perhaps a class with several methods)
– Bottom up approach• Starts with specific, detailed way of achieving
something(ie recursive area fill or interacting with a piece of hardware)
• Builds program up around that detail
Program design
3
Class Design• Design and implement a class• Design an interface (remember that an interface
has only methods, no data)• Extend a class using inheritance (Design question)• Remember that any class that implements an
interface must implement all methods in the interface
• Use extends and implements appropriately• declare constructors and methods with
– meaningful names– appropriate parameters– appropriate return types (remember constructors do not
have return types)
Class design
4
Class Design• appropriate declaration of methods as private or
public• all data should be private
Class design
5
1. Program ImplementationA. Classes that fill common needs should be
built so they can be reused by other programs. OO design is an important part of program implementation
B. Implementation Techniques1. Encapsulation and information hiding
2. Procedural abstraction
Program Implementation
6
C. Programming constructs1. Primitives vs references
1. Remember that references must be associated with an object
2. Beware of aliasing:when two references point to the same object
Program Implementation
7
Here is an explanation from borland’s web site;
D. Round-Off Problems : 1. One of the problems with floating point numbers is round-
off. Round off errors occur when attempting to represent certain numbers in any number base. For example, 1/3 is not exactly representable in base ten, while 1/10th is easily representable. But since we're dealing with computers, we are specifically in base two numbers. As opposed to base ten, 1/10th is not exactly representable in base two. For example, the fractional portions of base two are: 1/2 1/4 1/8 1/16 1/32 1/64 1/128 1/256 1/512 The numbers 1/2, 1/4, 1/8, all powers of two, are exactly representable in a computer. But since 1/10 lies between 1/8 and 1/16, it is not exactly representable using binary notation. So internally the computer has to decide which fractional binary portions to add together to sum close to 1/10. For example: 1/2 1/4 1/8 1/16 1/32 1/64 1/128 1/256 1/512 0 0 0 1 1 1 0 0 0 this adds up to: 0.1093 which is close to 0.1000 but could easily be rounded to .11 so the computer internal algorithm must try to find another combination of binary fractions which come closer to 0.1000 When it's internal algorithm is satisfied, it will have a number which is CLOSE to 1/10th but not EXACT. This inexactness is known as ROUND-OFF error.
Floating Point Number Probs
8
E. Constant declarations1. final double WIDTH = 1.1619;
2. Use these whenever you are using a numeric value that you type several places in a program
F. Variable declarations5. Scope of variables
1. Shadowing problem: Most local variable gets precedence
Constant Declarations
9
G. Method declarations1. A method’s signature consists of name,
parameter types and order of parameters2. Overloaded methods have the same name but
different parameters3. Constructors are often overloaded4. What is a static method?a method that does not
require an instance of the class to be created5. What is a private method?accessible only to class
member methods
Method declarations
10
H. Interfaces1. A collection of methods that a class must
implement2. An interface you should know
a)interface java.lang.Comparable
int compareTo(Object other)// return value < 0 if this is less than other// return value = 0 if this is equal to other// return value > 0 if this is greater than other
Interface Declarations
11
Example
Double x = new Double(1.618);
Double y = new Double(3.14159);
//Write a statement that compares x to y and prints out “phi is less than pi”
if (x.compareTo(y) < 0)
Interface Declarations
12
I. Math ops
1. +,-,/,*,%
2. two types of division
3. type casting (int) and (double)
4. Students are expected to understand "truncation towards 0" behavior as well as the fact that positive floating-point numbers can be rounded to the nearest integer as (int)(x + 0.5), negative numbers as (int)(x - 0.5)
5. Math.abs(double x), Math.sqrt(double x), Math.pow(double base, double exp)
Math Operators
13
J. Control techniques1. Methods2. break; //breaks out of nearest ________3. conditional (if, if else, switch case optional)4. iteration (for and while only required)5. recursion
a. Powerful technique when a method invokes itself
b. Must have some sort of stopping or base case
c. Remember to use McCarthy method or something similar to trace
d. many method calls decrease efficiency
Control
For each loop used heavily
The for each loop will probably be used heavily in the exam– ArrayList<String> songs = some list– Write a for each loop to print the songs
– int[] nums = some array of integers– Write a for each loop to find the average as a
double
14
15
Program Analysis– Testing/Debugging
• Test Libraries and Classes in isolation• Identify boundary cases
– Understand error handling• ArithmeticException
– Divide by zero• IndexOutOfBoundsException• ClassCastException
– Attempt to cast to subclass of which it is not an instance
• NullPointerException– Needed an object, got the shaft!!!
• IllegalArgumentException
Program Analysis
16
Algo Analysis– Big Oh Notation– Asymptotic growth limit– O(n) linear– O(n2) quadratic (two dim array, nested for)– O(logn) divide and conquer(assume base 2, this is
comp sci man!!)– O(1) constant time– O(nlogn) better sorting algo’s including logn= find
where this element belongs and n to move each element into position
Analysis of Algorithms
17
Analysis of AlgorithmsData Search Insert
(once the place is found)
Rem Get first
Array Unordered
Array Ordered
ArrayList
18
int : 32 bit signed integer double: 64 bit signed floating point boolean: true or false
Data Structures
19
Classes and Class Hierarchies
Remember chess piece example abstract base class with abstract method
isValidMove() Children must redefine this method Example of dynamic binding or late
binding Calls to isValidMove are _____________
20
Classes and Class Hierarchies
“Cast down the hierarchy” Ok to cast from Object to Integer assuming class
is an Integer Ok to cast from piece to pawn if you know the
piece is a pawn Children inherit all methods and classes (but
cannot play with ______________) Also, static methods and vars are one per class
21
One/Two dimensional arrays
Once created a certain size, fixed use .length, the member var Use [ ] to access elements starting at 0 …length-1 0 and <length works for boundaries Use array[0].length for column dimensions Use r and c for loop control vars for ease of
reading Must create individual objects if array of
references
22
ArrayList
int size() boolean add(Object x) Object get(int index) Object set(int index, Object x)
// replaces the element at index with x // returns the element formerly at the specified position
void add(int index, Object x) // inserts x at position index, sliding elements // at position index and higher to the right // (adds 1 to their indices) and adjusts size
Object remove(int index) // removes element from position index, sliding elements // at position index + 1 and higher to the left // (subtracts 1 from their indices) and adjusts size
23
Stacks
______________ data structures Good when you need to untangle some
type of operations that have to be suspended and returned to
24
Stack interface
public interface Stack { // postcondition: returns true if stack is empty,
false otherwise boolean isEmpty(); // precondition: stack is [e1, e2, ...,
en] with n >= 0 // postcondition: stack is [e1, e2, ..., en, x]
void push(Object x); // precondition: stack is [e1, e2, ..., en] with n >= 1 // postcondition: stack is [e1, e2, ..., e(n-1)]; returns en // throws an unchecked exception if the stack is empty
Object pop(); // precondition: stack is [e1, e2, ..., en] with n >= 1 // postcondition: returns en // throws an unchecked exception if the stack is empty
Object peekTop(); }
25
GridWorld GridWorld is an object oriented universe where
Actors can be called on to act() each step public Color getColor() { } public void setColor(Color newColor) { } public int getDirection() { } public void setDirection(int newDirection) { } public Grid getGrid() { } public Location getLocation() { } public void putSelfInGrid(Grid gr, Location loc) { } public void removeSelfFromGrid() { } public void moveTo(Location newLocation) { } public void act() { } public String toString() { }
26
GridWorld Location represents a row, col (y,x) in the
grid For convenience, Location also has
constants set up to handle the various directions
use getRow() and getCol() to get the y and x locations resepectively
27
GridWorld public static final int LEFT = -90; public static final int RIGHT = 90; public static final int HALF_LEFT = -45; public static final int HALF_RIGHT = 45; public static final int FULL_CIRCLE = 360; public static final int HALF_CIRCLE = 180; public static final int AHEAD = 0; public static final int NORTH = 0; public static final int NORTHEAST = 45; public static final int EAST = 90; public static final int SOUTHEAST = 135; public static final int SOUTH = 180; public static final int SOUTHWEST = 225; public static final int WEST = 270; public static final int NORTHWEST = 315;
28
GridWorld A BoundedGrid implements the Grid Interface It uses a ____________________ called
______________to store the elements private Object[][] occupantArray; // the array storing the
grid elements getNumRows() and getNumCols() will handle the
dimensions
29
GridWorld A BoundedGrid implements the Grid Interface It uses a ____________________ called ______________to store
the elements private Object[][] occupantArray; // the array storing the grid
elements getNumRows() and getNumCols() will handle the dimensions isValid(Location loc) is an important method to know public boolean isValid(Location loc) { return 0 <= loc.getRow() && loc.getRow() < getNumRows() && 0 <= loc.getCol() && loc.getCol() < getNumCols(); }
30
GridWorld public E get(Location loc) { if (!isValid(loc)) throw new IllegalArgumentException("Location " + loc + " is not valid"); return (E) occupantArray[loc.getRow()][loc.getCol()]; //
unavoidable warning } public E put(Location loc, E obj) {} public E remove(Location loc) {}
31
GridWorld Critters! public void act() { } public ArrayList getActors() {} public void processActors(ArrayList actors) { } public ArrayList getMoveLocations() { } public Location selectMoveLocation(ArrayList locs) {} public void makeMove(Location loc) { }
32
Strings class java.lang.String implements java.lang.Comparable int compareTo(Object other)
// specified by java.lang.Comparable boolean equals(Object other) int length() String substring(int from, int to)
// returns the substring beginning at from // and ending at to-1
String substring(int from)// returns substring(from, length())
int indexOf(String s)// returns the index of the first occurrence of s; // returns -1 if not found
Keep in mind substring first you want, first you don’t want. Also, there is a substring with only one argument, starts at that
char and goes to end substring probably a better idea that charAt, since chars not in
subset
Math.random()
All of the random() calls are made using Math.random()
This gives you a number between _______ and ________Example, use Math.random() to generate a # for choosing and element from an ArrayList called locations
33
34
Sorting Quadratic Sorts O(n2)
– Selection• Choose the maximal or minimal element by a loop and then swap
that with the current place you are moving through• Minimizes swaps
– Insertion• Pick an element, shift everyone out of the way to make room for
it (Church pew shuffle)– Bubble
• Nested for loops allow one element to “bubble” to the front or back each time
35
Sorting nlogn Sorts
– Merge• Start breaking up your list into smaller lists and merge them
together• Requires temporary storage area of size n for merging into
36
SortingSort Best Average WorstSelection
Insertion
Merge
37
Thats all folks!!!!• Neo journeyed to the machine city and faced off with Smith• Frodo took the ring to the Mountain of Doom• On May 3, you will accomplish your mission, the APCS exam• It is your purpose!