Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Review for the AP CS Exam  Object Oriented Program Design – Program Design Read and Understand class specifications and relationships among the classes.

Similar presentations


Presentation on theme: "1 Review for the AP CS Exam  Object Oriented Program Design – Program Design Read and Understand class specifications and relationships among the classes."— Presentation transcript:

1 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) A/B:Decompose a problem into classes, define relationships and responsibilities of those classes

2 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 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_____________________________ Use extends and implements appropriately declare constructors and methods with –meaningful names –appropriate parameters –appropriate return types (remember constructors _______________________________________) Class design

4 4  Class Design appropriate declaration of methods as private or public all data should be ______________ Class design

5 5 1.Program Implementation A. 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 Techniques 1.Encapsulation and information hiding 2.Procedural abstraction Program Implementation

6 6 C. Programming constructs 1.Primitives vs references 1.Remember that references must be associated with an object 2.Beware of aliasing:______________________________________ ________________________________________ Program Implementation

7 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 8 E. Constant declarations 1.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 declarations 5.Scope of variables 1.Shadowing problem: Most local variable gets precedence Constant Declarations

9 9 G. Method declarations 1.A method’s signature consists of name, parameter types and order of parameters 2.Overloaded methods have the same______________________ but different___________________ 3.Constructors are often overloaded 4.What is a static method?________________________________ _________________ 5.What is a private method?________________________________ __ Method declarations

10 10 H.Interfaces 1.A collection of methods that a class must implement 2.An interface you should know a)interface java.lang.Comparable  int compareTo(Object other) // return value 0 if this is greater than other Interface Declarations

11 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” Interface Declarations

12 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 13 J.Control techniques 1.Methods 2.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

14 14  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

15 15  Algo Analysis – Big Oh Notation – Asymptotic growth limit – O(n) linear – O(n 2 ) 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

16 16 Analysis of Algorithms DataSearchInsert (once the place is found) RemGet first Array Unordered Array Ordered ArrayList SLL with first ord SLL with first, last ord DLL first, last Stack Queue Bin Tree Hash Table

17 17  int : 32 bit signed integer  double: 64 bit signed floating point  boolean: true or false Data Structures

18 18 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 _____________

19 19 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

20 20 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

21 21 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

22 22 Linked Lists  Singly  Doubly  Circular  Inserting, must use a trailer to link the previous node to new node (remember to use new command to create) and link this node to next  When removing, just point the previous node to this node’s next and the Java garbage collection will scoop up the idle node

23 23 List Node public class ListNode { public ListNode(Object initValue, ListNode initNext) { value = initValue; next = initNext; } public Object getValue() { return value; } public ListNode getNext() { return next; } public void setValue(Object theNewValue) { value = theNewValue; } public void setNext(ListNode theNewNext) { next = theNewNext; } private Object value; private ListNode next; } Must typecast when pulling something out of the list, NOTE: Need have some way to compare if you intend to use a sorted list

24 24 Stacks  ______________ data structures  Good when you need to untangle some type of operations that have to be suspended and returned to

25 25 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(); }

26 26 Queues  ______________ data structures  Good when you need to simulate some sort of time dependent operation  Good for holding items to be processed over time

27 27 Queue Interface public interface Queue { // postcondition: returns true if queue is empty, false otherwise boolean isEmpty(); // precondition: queue is [e1, e2,..., en] with n >= 0 // postcondition: queue is [e1, e2,..., en, x] void enqueue(Object x); // precondition: queue is [e1, e2,..., en] with n >= 1 // postcondition: queue is [e2,..., en]; returns e1 // throws an unchecked exception if the queue is empty Object dequeue(); // precondition: queue is [e1, e2,..., en] with n >= 1 // postcondition: returns e1 // throws an unchecked exception if the queue is empty Object peekFront(); } REMEMBER To ________________________all objects you pull out as needed

28 28 Binary Trees  Ordered ones are called _____________  Heaps have _______________________________  Powerful divide and conquer structure

29 29 Binary Trees  Traversals F CR M Pre: In: Post:

30 30 Priority Queues  Queue that allows high priority items to move to the top (the minimal element) public interface PriorityQueue { // postcondition: returns true if the number of elements in // the priority queue is 0; otherwise, returns false boolean isEmpty(); // postcondition: x has been added to the priority queue; // number of elements in the priority queue is increased by 1 void add(Object x); // postcondition: The smallest item in the priority queue is removed // and returned; the number of elements in the priority queue // is decreased by 1 // throws an unchecked exception if the priority queue is empty Object removeMin(); // postcondition: The smallest item in the priority queue is returned; the // priority queue is unchanged // throws an unchecked exception if the priority queue is empty Object peekMin(); }

31 31 To Be Continued… More tomorrow

32 32 Analysis of Algorithms DataSearchInser t RemGet first Array UnorderedO(n)O(n) shift O(1) Array OrderedO(logn) bin s O(n) shift O(1) ArrayListO(n)O(n) shift O(1) SLL with first ordO(n)O(1) SLL with first, last ord O(n)O(1) DLL first, lastO(n)O(1) StackO(n)O(1) alwa ys top O(1) top O(1) top QueueO(n)O(1) Bin TreeO(logn) Hash TableO(1)

33 33 Sets  A set is a collection of unique objects  Does not allow ________________________ interface java.util.Set boolean add(Object x)adds element, returns true if successful boolean contains(Object x) returns true if x occurs in Set boolean remove(Object x) attempts to remove x, true if successful int size() returns number of elements in the Set Iterator iterator() returns an Iterator for the set

34 34 Sets  TreeSet keys must implement________________  A TreeSet gives you a balanced ______  To get the values in order___________________________________ _________________________________  HashSet needs a key that redefines ___________ and ______________  If you add a pair that has an existing key, __________________________

35 35 Maps  A map is an association of _________ and __________ interface java.util.Map Object put(Object key, Object value) // associates key with value // returns the value formerly associated with key // or null if key is not in the map Object get(Object key) Object remove(Object key) boolean containsKey(Object key) int size() Set keySet()

36 36 HashMaps  HashMaps implement a hash table – (Use.75 full max as a guideline)  Uses your hashCode( ) method that is redefined as part of Object (but how do you know how big the table is?)  True or False: You are guaranteed to get the keys in order if you iterate over the keySet  The key used must be a distinct object, which is why I think HashMaps are stupid!!!

37 37 TreeMaps  TreeMaps implement a balanced BST  All of the work of inserting and traversing is done for you  Your keys must implement ______________  Once again, your keys must be a distinct object, which is pretty hokey  Attempting to insert a duplicate key will___________________________

38 38 Iterators  Iterators allow traversal of a data set using a common iterface  java.util.Iterator – boolean hasNext() – Object next();//will need to typecast this result – void remove(); //must be called after next  Think of an iterator as a flashing cursor between the letters of text

39 39 ListIterators  ListIterators add _______________ and ______________ to the Iterator – __________________ Get a ClassCastException if adding an element that is not like the others Subsequent calls to next() unaffected by add – _____________________ IllegalStateException if next() not called or if remove or add called since last call to next()  You can always reset a iterator to the front of the list be recreating it

40 40 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

41 41 Priority Queues public interface PriorityQueue { // postcondition: returns true if the number of elements in // the priority queue is 0; otherwise, returns false boolean isEmpty(); // postcondition: x has been added to the priority queue; // number of elements in the priority queue is increased by 1 void add(Object x); // postcondition: The smallest item in the priority queue is removed // and returned; the number of elements in the priority queue // is decreased by 1 // throws an unchecked exception if the priority queue is //empty Object removeMin(); // postcondition: The smallest item in the priority queue is returned; the //priority queue is unchanged //throws an unchecked exception if the priority queue is empty Object peekMin(); }

42 42 Implementing P Queues  All items in a priority queue must implement __________________  There are many ways to implement a priority queue  The most interesting to me is with a Heap  A heap is _________________________________  The root contains the smallest element therefore removeMin is O(___)  Then the heap must be reheaped which is O(____)  This is cool

43 43 MBCS  The MBCS consists of interfaces – Environment – Locatable – EnvDisplay  Classes(Visible) – Simulation – Fish – DarterFish – SlowFish – SquareEnvironment(Abstract) (Ch 5 – A/B only) – BoundedEnv – UnBoundedEnv  Classes(Black Box) – Debug – Direction – Location – RandNumGenerator

44 44 MBCS  To Start – A program will create an environment and a display and then either Add the fish manually one at a time or ____________________________________ – Then a program will create a environment Display – A Simulation Object is created and the Environment and environment display are passed to it – Simulation asks the Environment for a list of Fish – What is the order of the fish in the array? – Locatable[] theFishes = theEnv.allObjects(); – for (int index = 0; index < theFishes.length; index++) ( (Fish) theFishes[index]).act();

45 45 MBCS  Valid Example Files (Empty file OK, two fish in same loc == joo got a problem, esse) bounded 10 10 Fish 0 0 North Fish 0 1 South Fish 0 2 East Fish 0 3 West Fish 0 4 North Fish 0 5 South Fish 0 6 East Fish 0 7 West Fish 0 8 North unbounded DarterFish 5 5 North DarterFish 3 3 South DarterFish 10 10 East DarterFish 6 8 West DarterFish 2 10 North DarterFish 1 1 South

46 46 MBCS  BoundedEnv – Stores fish in what type of data structure?_____________________________________ – Fish ask to be added to the environment from their initialize method – When does BoundedEnv reject the fish’s request? – ______________________________________ – public void recordMove(Locatable obj, Location oldLoc) records the move by updating the array if it was valid sets the old location in the array to ______________

47 47 MBCS  UnBoundedEnv – Uses an ArrayList called objectList – protected int indexOf(Location loc) //This method will get the index of where a fish living at loc is stored in the ArrayList or –1 if loc has no fish living there – Example – Fish at 0,4 6,3 and 6,5 – objectList = (0,4), (6,3), (6,5) – env.indexOf(new Location(6,5)) returns 2 – returns –1 for numRows() and numCols() – A/B’ers should look this over this weekend

48 48 MBCS  Fish – Is there a direction that a fish cannot move in? – ________________________________ – Where is this accomplished?_____________________  private void initialize(Environment env, Location loc, Direction dir, Color col) – fish use this to set initial values  public void act() //(with breeding and dying turned on) – Use isInEnv to see if fish is alive in env and where it thinks it is – Try to breed by calling breed method (default prob is 1/7) Find any empty neighbors Fill them with child fishes (same color as parents) This is not the way it works in real life, boys, in case you fell asleep in health!!!!

49 49 MBCS  public void act() //continued – If the fish did not breed, try to move by calling the move method (nextLocation plays a big role here) Change the fish’s direction to the direction they just moved – Obtain a random object to see if this fish will die in this timestep Default probability is ___________

50 50 MBCS  Darter Fish – extends fish, overrides generateChild, nextLocation, move – How does a da’ta move? – _______________________________________  SlowFish – extends fish, overrides generateChild and nextLocation – How does a slow fish move? – ________________________________________  Polymorphism, late binding, cool stuff

51 51 MBCS  A good example of OO Programming – Each class has its own responsibility – The class dependencies are limited, so changes can be made more easily – Inheritance hierarchy is a powerful concept

52 52 Sorting  Quadratic Sorts O(n 2 ) – 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)

53 53 Sorting  nlogn Sorts – HeapSort Form a heap from your elements (O(n) work here) Take the last unsorted element and swap it with root Reheap and do this process over and over again – Merge Start breaking up your list into smaller lists and merge them together Requires temporary storage area of size n for merging into – Quick Pick a pivot Start finding stuff pivot and swapping Put the pivot in place Quicksort(0,pivot-1) and Quicksort(pivot+1,n) Keep doing this until all partitions are sorted Does crappy for sorted lists already

54 54 Sorting SortBestAverageWorst Selection Insertion Merge Heap Quick

55 55 Thats all folks!!!! In November, Neo journeyed to the machine city and faced off with Smith In December, Frodo took the ring to the Mountain of Doom In May, you will accomplish your mission, the APCS exam It is your purpose!


Download ppt "1 Review for the AP CS Exam  Object Oriented Program Design – Program Design Read and Understand class specifications and relationships among the classes."

Similar presentations


Ads by Google