CSCI 1620 - Final

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Three Fundamental Questions

*1) Base Case Question* - Does the algorithm provide one or more non-recursive ways out *2) Smaller-Caller Question* - Does each call to the method work on a smaller sub-problem of the original and - Will these smaller versions eventually lead to one of the base cases? - Will case a StackOverFlow error if this is not asked and answered *3) General-Case Question* - If we assume the recursive call works, would the algorithm produce the intended result?

Final Classes

- Abstract allows us to define a thing as "incomplete" - Final allows us to define a thing as "totally complete" - If a class is final, it cannot be inherited - This class is specific as it gets, it can not be built upon

JUnit 4 Test

- Add suffix "Test" or "Tests" - @Test before test method (like @Override) - Always void & no parameters usually Ex: public void testEQualFractions() { assertionTrue(f1.equal(f2)); }

Formal Testing Strategies

- Black Box Testing - White Box Testing

Decomposition

- Classes represented a *single coherent entity* with clearly defined responsibilities - Methods serve a single, simply described purpose

Encapsulation & Information Hiding

- Classes should bring together all of the relevant data and behaviors for an entity - Member data of object should be controlled exclusively by the class itself

Selection Sort

- Data set is logically split into a "Sorted & not sorted" section, indicated by an index, to begin, the active set is "not sorted" - Performs n-1 passes - n + # of items in data set

Insertion Sort

- Data set is logically split into a "sorted & not sorted" sections, indicated by an index - To begin the first element in the "sorted" section, all other elements are "Not Sorted" - "Sorted" sections items are only guaranteed to be sorted relative to other items in the "sorted" section - Perform n-1 passes (n = # of items in the data)

Over-Arching Goals of OOP

- Decomposition - Encapsulation & Information Hiding

Generics

- Generics allow programmers to define a temporary, unspecified type as a place holder when writing a method - When the method is called, the specific type to be used for that call is determined by the context of the arguments passed

Where to start when creating a Class?

- Incrementally, testing as you go

Inheritance Mechanism - Cont.

- Inheritance relationships may cascade in a hierarchy - Java only supports single inheritance between any two classes at a time So you can't do: 'public class C extends B, C; //this is illegal'

How do recursive methods execute?

- Just like with non-recursive methods each function is tracked separately in the JVM call stack. They are resolved in Last-In-First-Out order - Once the base case is encountered, the most recent invocation returns to its caller - Genera/recursive cases complete their pending computation and return to their caller

Classes

- Like a blue print - Allows us to create individual instances of the kind of thing - Each individual instance shares some prop. & behaviors - But each instances can have difference *values* for the prop. Ex: Every house has a color, but each house may have a difference color - Fraction f1 = new Fraction(1, 2); Fraction f2 = new Fraction(7, 10);

Simple Recursive Algorithms (Linear)

- Make only a single recursive call in each general case - They make the problem "a bit" smaller each step toward the base case

Complex Data Types

- Member data (fields) - Instance data - Class data

Why sort data?

- Most data needs managed - Display to use in a specific way - Processed in a certain order to be used

What is required to write Classes?

- Must be defined in a file that has the same name of the class with '.java' file extension (every '.java' file can have *one* public class defined)

Other forms of Recursive Problems

- Non-linear subproblem structure (Binary search, fibonnaci) - Multiple base cases and/or recursive cases - Indirect Recursion (methodA calls methodB which calls methodA)

Comparable - Interface

- One of the most common interfaces - IT defines a single abstract method "compareTo", which is expected to be implemented as all relational operations: equal to, greater than, and less than

JavaDoc - Tags

- Starts with @ - Are case-sensitive Ex: @return - IF the method returns a value, a single @return tag is used to describe what is returned @param - Each parameter of the method is giving its own @param tag with the name of the parameter and a description of what it is used for

Our Goal when Testing

- To create a test plan that exercises all paths of code execution, regardless of how common - Develop a suite of reusable test that can be easily re-run to verify our code along the way and at the end - All tests must be valid and compile

Static

- Underlined in UML, its class data - To access a static member, we use the class name (rather than a reference variable) on the left side of the dot operator Ex: Fraction.setSeperator(':'); Fraction f1 = new Fraction(1, 2);

When to use Recursion in Java

- When the problem can be defined in terms of itself - When the depth will not get "too large" while solving the problem (Ex: <500 calls or so) - Especially if the problem seems "divide & conquer"-able by breaking the problem set down in large steps (Like a merge sort, limited depth) - Where you don't have (or can prevent) recomputation along the way - Where the final code naturally corresponds to the structure of the problem

Concrete Class

- not an abstract class - A concrete class cannot have unimplemented abstract methods or else it will not compile

JavaDoc - Comments

/** * a multiline JavaDoc Comment */

Simple Recursive Algorithms (Linear) - Steps

1) Check Base Case 2) General/Recursive Case (If not the base case) 2.1) Process "First Item" 2.2) Recurse on "the rest" 2.3) Combine results of first item processing with the recursion results and return

Insertion Sort - Steps

1) Grab the first item in the "Not Sorted" section 2) Shift items in sorted section to make room for the next item, insert item into place 3) Increase the size of the "sorted" section by one - Items are "sorted" relative to one another, rather than the whole array

Steps of a Selection Sort

1) Perform n linear search through the "Not Sorted" section to find (Select) the "smallest" item in the set 2) Swap this item with the first item in the "Not Sorted" section 3) Increase the size of the "Sorted" section by one

Reference Type Equality

10 = 10 will copy memory address, not make a copy use ".equals()" instead

Abstract Classes

A class can be declared as *abstract* by using the "abstract" keyword in the class definition - to denote in UML, {abstract} below class name - Abstract classes cannot be instantiated

Test Driver

A class is designed to help verify another class functions correctly - Informal, can get edited & deleted as you program

JUnit

A framwork for writing reusable unit tests - There is a lbray build on a series of "assertion methods" Ex: assertTrue(observedVal)

Dependency

A place where one class depends on ("Uses") another class in some way. - UML visualizes simple usage dependencies using a dotted arrow to indicate which class uses which. - "Use" Dependencies are the simplest relationship between classes - Can Occur between classes & Methods within a class - Understanding dep. can help us determine the order in which code should be implemented and tested - Minimizing the # of dep. between classes improves the robustness of the solution with respect to future changes Ex: User's Adopt method has a Pet parameter

Non-Linear Recursion

A recursive process that includes multiple recursive calls inside of a method, such as tree traversal methods that first traverse one branch of the tree from that node, and then the other branch. Example: - Print all #s - Solve towers of Hanoi - Catalog all pages on the web (Like google)

Downcast

A reference is being cast down to its subtype. EX: int left = numerator * ((Fraction) other).denominator;

Interfaces

A type that is more abstract than a class - Defines abstract methods, any class that implements an interface must implement the methods define in the interface - Interfaces are used to grant common behaviors to otherwise unrelated classes - While a class can only have a single direct super-class, they can implement as many interfaces as needed - Implementing an interface also grants an Is-a relationship allowing for polymorphic behavior

Which of the following are benefits of abstract classes? Select all that apply. A) Enforce subclasses to provide implementation of abstract behaviors through abstract methods B) Since the class is abstract it is not necessary for it to be compiled C) Provides a default behavior for subclasses through abstract methods D) Ensures that instances of the class cannot be made, since they are incomplete

A) Enforce subclasses to provide implementation of abstract behaviors through abstract methods D) Ensures that instances of the class cannot be made, since they are incomplete

Which of the following could result in a StackOverflowError while a program is running? (Select all that apply) A) Failing to write a base-case in a recursive method. B) Providing parameter values that match the base case on the first method call. C) Parameter values that require a large number of recursive calls to compute. D) A series of recursive calls whose parameter values never approach the base case.

A) Failing to write a base-case in a recursive method. C) Parameter values that require a large number of recursive calls to compute. D) A series of recursive calls whose parameter values never approach the base case.

Which two sorting algorithms discussed share the same best case run time when the items are already in sorted order? A) Insertion Sort B) Selection Sort C) Bubble Sort D) Bubble Sort with Early Exit

A) Insertion Sort D) Bubble Sort with Early Exit

Which sorting algorithm discussed uses a modified version of a linear search? A) Selection Sort B) Insertion Sort C) Bubble Sort with Early Exit D) Bubble Sort

A) Selection Sort

Which of the following is not true about a linear recursive algorithm? A) The linear recursive version of an iterative algorithm will generally perform faster in Java. B) Linear recursive algorithms do not need for or while loops to process collections of data. C) Linear recursive definitions leverage the fact that the problem can be defined in terms of a sub-problem that closely resembles the original problem. D) Each call in a linear recursive method is responsible for processing a single item.

A) The linear recursive version of an iterative algorithm will generally perform faster in Java.

What is polymorphism good for?

An object can be referred to as anything it "Is"

A recursive helper method __________ (select all that are true) A) Should only be used when recursing on arrays. B) Allows you to add parameters to simplify the recursive calls on a method, but forces external code to use a more restricted parameter list. C) Will generally have the same return type as the original method. D) Must be written for every method that we'd like to define recursively.

B) Allows you to add parameters to simplify the recursive calls on a method, but forces external code to use a more restricted parameter list. C) Will generally have the same return type as the original method.

When defining a type parameter, it must be enclosed in which of the following: A) Curly Braces { } B) Angle Brackets < > C) Square Brackets [ ] D) Parenthesis ( )

B) Angle Brackets < >

In UML notation, abstract classes and methods are denoted by what? A) Underlined B) Italicized C) Surrounded by { } D) Bolded

B) Italicized

Setting a bounds for a type parameter uses which keyword? A) bounded B) extends C) Implements D) Depends if you are setting the bounds as a class or an interface

B) extends

If there is an algorithm that uses three nested for loops: for ... for ... for ... Where each for loop traverses some percentage of the same array of length n, the efficiency of that algorithm would be said to be of the order (the ^ in the answers represent exponentiation): A) n ^ 2 B) n ^ 3 C) n

B) n ^ 3

Select all true statements about the recursive MergeSort algorithm: A) It will always perform better than InsertionSort, regardless of the dataset. B) Based on the definition in the video, Mergesort is a linear recursive algorithm. C) In many cases, it performs dramatically faster than InsertionSort. D) For a fixed array size, MergeSort will always take the same amount of time to run.

C) In many cases, it performs dramatically faster than InsertionSort. D) For a fixed array size, MergeSort will always take the same amount of time to run.

Which of the following would be the correct class header for an abstract Dog class? A) public class Dog abstract B) abstract public class Dog C) public abstract class Dog D) public class abstract Dog

C) public abstract class Dog

Which method should we start with?

Cannot instantiate a class without a constructor

A reference is capable of referring to which of the following? Select all that apply. A) An instance of the same type as the reference B) A reference can refer to any type of object C) An instance of a superclass of the reference D) An instance of a subclass of the reference

D) An instance of a subclass of the reference

Which sorting algorithm discussed shifts elements to make room for the next sorted item? A) Selection Sort B) Bubble Sort with Early Exit C) Bubble Sort D) Insertion Sort

D) Insertion Sort

Which is true about a recursive method that fails the re-computation question (ie, it computes the same value in multiple recursive calls): A) This method would result in an infinite recursion. B) This method would not compile. C) This method would finish, but compute the wrong value. D) This method could finish eventually with the correct result, but might take a long amount of time to compute.

D) This method could finish eventually with the correct result, but might take a long amount of time to compute.

The Java operator that can be used to determine what type of object a reference is referring to at runtime is: A) objecttype B) istype C) isa D) instanceof

D) instanceof

If I'd like to define class a Student to be a subclass of class Person, which of the following is the correct header for Student? A) public class Student super Person B) public class Student inherits Person C) public class Student extend Person D) public class Student extends Person

D) public class Student extends Person

The DRY Rule of OO Design

Don't Repeat Yourself

Member Methods

Example: equals

Has-A Relationship

Exists between two classes when objects of one class have references to other classes for instance variable - Stronger than "Use" association Ex: A car has an engine, tires, radio

A reference that is referring to a subclass object can directly access any of the public members of the subclass. True or False?

False

References of abstract classes cannot be created. True or False?

False

The call stack of the Java Virtual Machine processes calls to recursive methods differently than non-recursive method calls. True or False?

False

When calling upon a Generic method, the type parameter can be satisfied by either a primitive or reference type. True or False?

False

compareTo

Given an object and return one of the following: - 0 if the two objects are equal - A value of <0 if the calling object is less than the passed object - A value of >0 if the calling object is greater than the passed object - Can extend & implement in the same class

ADD NOETS FROM ALL CHAPTER

I have not done that yet

Inheritance Mechanism

If objects of B are also objects of A, we say: - A is a *superclass* of B - B is a *subclass* of A - B *inherits* the variables and methods defined in A

What do Primitive Wrappers look like?

Integer[] intArr = {5, 6}; Interger[] doubleArr {3.3, 6.7}

The code below is a broken linear recursive implementation of linear search. What's wrong with it? public static findIt(int item, int[] list) { if (list == null) return false; else if (list[0] == item) return true; else return findIt(item, list); }

It fails the smaller-caller question.

Variables

Named locations in memory where we can store values

JavaDoc

Provides a standardized format for documenting the expected behavior of classes. - Should be written when a new class is created so that others can quickly learn about how to use it - Typically, we read "Public JavaDoc," not private as 3rd party clients - Command Line Tool (Can generate HTML Document)

Degression Testing

Re-run unit and integration test when changes are made to existing code to verify your "fix" didn't accidentally break something else

Primitive Wrappers

Reference types that mirror primitive types - Many translations from primitive to primitive wrapper & vice versa is automatic - Allows for primitive with Generics - Does not apply for array of primitives

Linear Recursion

Refers to an algorithm that makes a single recursive call each step, letting the recursive calls walk through the data similar to how a loop counter would. - Often more memory intensive and slower than the iterative form due to method calls and pending computations - StackOverflowExceptions may occur even when there is not an infinite recursion, can just be too deep

Linear Search

See photo

JavaDoc - Methods

Should Include: - What a method returns - What a method takes as arguments - Describe what the method does (summary)

Black Box Testing

Testing functionally with no knowledge of internal implementation - Cannot see code/system

Unit Testing

Testing individual classes/methods as you implement to check completeness and correctness - Ideally, test cases are written first to be benchmark as you implement

White Box Testing

Testing the functionality with knowledge of internal implementation - More robust

Integration testing

Testing used for verifying the interactions of multiple modules/systems

Polymorphism

The ability to take different forms - Very important concept - An instance of something can be refered to by any multiple forms (morph)

Data Types

The range of acceptable values - A set of allowable operations - 8 primitive data types

Type Parameter - Generics

The temporary type that is treated like a reference type - can only be used as a place holder for reference types

instanceof

This operator returns true if the object referenced by the left side has an "Is-a" relationship with the type on the right side - To check if casting is valid

Abstract Methods

Those that define a method, but do not, and cannot, provide implementation - Implementation is left up to the sub-class to determine - A class that inherits from an abstract class inherits all of its members, including any unimplemented abstract methods - In UML, name is italicized and usually includes {abstract} for clarity

Which of the methods below is a non-linear recursion? Trickery, Mystery, or Illusion? public static String mystery(String s) { if (s.equals("")) return ""; else if (s.length() == 10) return s; else return mystery(s.subString(0, s.length - 2)) + s.charAt(s.length - 1); } public static int trickery(int x) { if (x <= 0) { return 1; } else { int sum = x; sum += trickery(x - 10); sum += trickery(x / 100); return sum; } } public static int illusion(int x) { if (x == 20) return 0; else if (x < 20) return illusion(x + 1); else if (x >20) return illusion(x % 20); }

Trickery

It is possible to create an array of interface references. ex. Given that Serializable is an existing interface: Seriallizable[] serArr = new Serializable[10]; True or False?

True

When a reference is referring to a subclass object, and calls upon a method that is overridden in the subclass, the implementation that will be executed is the one defined in the subclass. True or False?

True

Multiplicity

UML allows us to indicate more details about *how many objects* of a given class are present in the relationship

Is-A Relationships - UML

Use up arrow

Object-Oriented Design Strategy

What kind of *objects* will we need? A: Look for nouns What kinds of *behaviors or methods* should each object be able to do? A: Look for verbs (methods are about doing things, so you would use a verb) What kinds of *data* should each object type store? A: Consider nouns and/or adjectives

Composition

When Objects of class A contains references to objects of Class B as instance variables and the objects of class B do not exist without A objects around Ex: If your car is broken than you assume so are the parts of the car

Dynamic Bonding

When a super-class reference is assigned to a subclass object and an overridden method is called, the JVM determines at run time which method to call based upon the type of the object being referred to, not *how* it is referred to.

Is-A Relationship

When an object of one class can be considered logically also an object class - We leverage is-a relationships to extract commonalities thereby increasing reuse-ability and maintainability in our system Ex: - A student *is-a* person - A dog *is-a* pet

Aggregation

When objects of class A contain references to objects of class B as instance variables, but B objects may exist in the system without A objects around

Example of Abstract Class

public abstract class Employee { }

Abstract Method Example

public abstract double compuyPaycheck();

Class - Syntax

public class ClassName { //everything inside the class }

When using a superclass in a subclass use:

public class ClassName *extends* NameSuperClass;

To invoke the constructor or superclass:

super(parameters) - Have to do this on the 1st line inside subclass constructor

JavaDoc - Make it look like Code

{@code ____}


Set pelajaran terkait

Abeka American Literature App Quiz HH

View Set

NUR 424 MEDSURG QUIZ on Immune Deficiency (chapter 36)

View Set

Nurse Practice Act and Legal Liability

View Set

Geology Chapter 7 - Sedimentary environments and rocks

View Set

WWCC Nursing Practice Calculations

View Set

Organizational Behavior: Chapter 8

View Set