Upload
rolf-miller
View
219
Download
3
Embed Size (px)
Citation preview
CS 121Week 15 – Friday
What did we talk about last time? Student Questions Review up to Exam 2
Loops Arrays StdDraw StdAudio Static methods
Questions?
Project 5
Review
Student Questions
Objects
A reference is just an arrow If you declare a lot of references, you
have not created any objects, just lots of arrows (unlike primitive types)Eggplant aubergine;
DumpTruck truck1;Idea thought;
aubergine truck1 thought
Calling a constructor
To make a new object, you use the new keyword with the name of the class followed by parentheses:
Perhaps there is a Ham constructor that lets you take a double that is the number of pounds that the ham weighs:
Ham ham1 = new Ham(); //default constructor
Ham ham2 = new Ham( 4.2 ); //weight constructor
Calling methods
You are already familiar with calling methods on Strings
So, applying this knowledge to other objects should be a piece of cake
Simply type the name of the object, put a dot, then type the method name, with the arguments in parentheses:String s = new String("Help me!");
char c = s.charAt(3); //c gets 'p'
Calling methods on objects Just like calling methods on String objects:
You’ve learned lots of methods that work on String objects
Every kind of object has its own methods You’ll have to learn them (or look them up)
if you want to use them
Ham h = new Ham(3.2);h.bite(); //takes bite out of hamdouble weight = h.getWeight(); //gets current ham weight
Equivalence confusion
In this example, the == operator will say they are different, but the equals() method will say that they are the same
Every object has an equals() method
String s1 = new String("identical");String s2 = new String("identical");if( s1 == s2 )System.out.println("Same!");
elseSystem.out.println("Different!");
if( s1.equals( s2 ) )System.out.println("Same!");
elseSystem.out.println("Different!");
Classes
Templates for objects An object is the actual data that you can use
in your code A class is a template whereby you can
create objects of a certain kind Class = Car Object = Mitsubishi Lancer Evolution X
Just like int is a type and 34 is an instance of that type
A key difference is that you can define new classes
Classes contain members and methods
Anatomy of a class definitionpublic class Name {
private int member1;private double member2;private Hedgehog member3;
public Name() {
…}
public int method1( double x ){
…}
}
Class definitionMember
declarations
Constructor definition
Methoddefinition
Members are data inside an object Members are the actual data inside
an object They can be primitive types or other
object types They are usually hidden (private)
from the outside worldpublic class Point {private double x; // member variableprivate double y; // member variable
}
Data visibility
private and public allow you to specify the scope or permissions of members and methods
private means that only methods from the same class can access an item
public means that any method can access the item
protected means that child classes can access the data (but not someone outside of the inheritance hierarchy)
Methods are ways to interact with objects Methods allow you to do things Object methods usually allow you to
manipulate the members They are usually visible (public) to
the outside world Methods can be static or non-static Only non-static methods can interact
with the members of an object
Constructors
Constructors are a special kind of method
They allow you to customize an object with particular attributes when it is createdpublic class Point {
private double x; // member variableprivate double y; // member variable
public Point( double newX, double newY ) { //constructorx = newX;y = newY;}
}
Accessors
Because members are usually private, it is common to use methods specifically just to find out what their values are
A method that just returns the value of a member variable is called an accessor
public double getX() { //accessor for xreturn x;}
public double getY() { //accessor for yreturn y;}
Mutators
Again, because members are usually private, it is common to use methods specifically just to change their values
A method that just changes the value of a member variable is called a mutator
public void setX( double newX ) { //mutator for xx = newX;}
public void setY( double newY ) { //mutator for yy = newY;}
Class Variables
Static members
Static members are stored with the class, not with the object
public class Item {private static int count = 0; //only one copy (in class)private String name; //one copy per object
public Item( String s ) {name = s;count++; //updates global counter}
public String getName() { return name; }
public static int getItemsInUniverse() { return count; }}
Static rules
Static members are also called class variables
Static members can be accessed by either static methods or regular methods (unlike normal members which cannot be accessed by static methods)
Static members can be either public or private
Members can be constant Sometimes a value will not change
after an object has been created: Example: A ball has a single color after
it is created You can enforce the fact that the
value will not change with the final keyword
A member declared final can only be assigned a value once
Afterwards, it will never change
Big Oh Notation
Mathematical description We want to compare the running
time of one program to another We want a mathematical description
with the following characteristics: Worst case
We care mostly about how bad things could be
AsymptoticWe focus on the behavior as the input size gets larger and larger
Inadequacy of running time function Just adding up the total operations in code is
not very helpful because: It cannot be used to give us an idea of how long
the program really runs in seconds It is complex and unwieldy
The most important thing about the analysis of the code that we did is learning that the growth of the function should be linear
A general description of how the running time grows as the input grows would be useful
Big Oh notation
Enter Big Oh notation Big Oh simplifies a complicated running
time function into a simple statement about its worst case growth rate
All constant coefficients are ignored All low order terms are ignored 3n + 3 is O(n) Big Oh is a statement that a particular
running time is no worse than some function, with appropriate constants
Big Oh simplification examples 147n3 + 2n2 + 5n + 12083 is
O(n3)
n1000 + 2n isO(2n)
15n2 + 6n + 7log n + 145 isO(n2)
659n + nlog n + 87829 isO(n log n)
Note: In CS, we use log2 unless stated otherwise
Hierarchy of complexities Here is a table of several different complexity
measures, in ascending order, with their functions evaluated at n = 100
Description Big Oh f(100)Constant O(1) 1
Logarithmic O(log n) 6.64Linear O(n) 100
Linearithmic O(n log n) 664.39Quadratic O(n2) 10000
Cubic O(n3) 1000000Exponential O(2n) 1.27 x 1030
Factorial O(n!) 9.33 x 10157
Searching and Sorting
Search algorithm For a linear search, we just look through every
element in the array until we find it or run out
If we find it, we return the index, otherwise we return -1
This takes O(n) time where n is the length of the array
public static int find( int[] array, int number ) {for( int i = 0; i < array.length; i++ )if( array[i] == number )return i;
return -1;}
Binary search
We can search faster if the array is already sorted by playing a high-low game
Repeatedly divide the search space in half
We’re looking for 37, let’s say5423 31
Check the middle(Too high)
Check the middle(Too low)
Check the middle(Too low)
Check the middle(Found it!)
37
Running time for binary search We cut the search space in half every time At worst, we keep cutting n in half until we
get 1 Let’s say x is the number of times we look:
The running time is O(log n)
log n = x n = 2x
x
21 n = 1
Bubble sort is a classic sorting algorithm It is very simple to understand It is very simple to code It is not very fast The idea is simply to go through your
array, swapping out of order elements until nothing is out of order
Code for a single pass
One “pass” of the bubble sort algorithm goes through the array once, swapping out of order elements
for(int j = 0; j < array.length - 1; j++)if( array[j] > array[j + 1] ) {
int temp = array[j];array[j] = array[j + 1];array[j + 1] = temp;
}
Full bubble sort code
The full Java method for bubble sort would require us to have at least n – 1 passes
Alternatively, we could keep a flag to indicate that no swaps were needed on a given pass
for(int i = 0; i < array.length – 1; i++)for(int j = 0; j < array.length - 1; j++)if( array[j] > array[j + 1] ) {int temp = array[j];array[j] = array[j + 1];array[j + 1] = temp; }
Color and Images
RGB One system for representing color is
RGB With Red, Green, and Blue
components, you can combine them to make most visible colors
Combining colors is an additive process: With no colors, the background is black Adding colors never makes a darker color Pure Red added to pure Green added to
pure Blue makes White RGB is a good model for computer
screens
Color class
The Color class is how Java keeps track of colors, using an RGB model
To use it, you need to type import java.awt.Color; at the top of your program (before the class declaration)
Each Color object represents one of 16,777,216 different colors with a value between 0-255 for Red, Green, and Blue
To use Color
To create a custom color:
Create colors using the constructor to specify RGB values
Get individual values using: getRed() getGreen() getBlue()
Color c = new Color(255,165,0); //orange int green = c.getGreen();
Luminance If the R, G, B values happen to be
the same, the color is a shade of gray 255, 255, 255 = White 128, 128, 128 = Gray 0, 0, 0 = Black
To convert a color to a shade of gray, use the following formula: Value = .3R + .59G + .11B
Based on the way the human eye perceives colors as light intensities
Horizontal mirror example
0 1 2
0 A
1 B
2 C
3 D
0 1 2
0 A
1 B
2 C
3 D
Original Mirrored
Horizontal mirror in code Using the picture class, here is the
code for mirroringPicture picture = new Picture( file ); //the picture to be mirrored
Picture mirrored = new Picture( picture.width(),picture.height() );
for( int i = 0; i < picture.width(); i++ )for( int j = 0; j < picture.height(); j++ )mirrored.set( picture.width() - i - 1, j, picture.get( i, j ) );
Right rotation example
0 1 2
0 A
1 B
2 C
3 D
0 1 2 3
0 D C B A
1
2
OriginalRotated
Rotation in code
Using the picture class, here is the code for rotation
Picture picture = new Picture( file ); //the picture to be rotated
Picture rotated = new Picture( picture.height(), picture.width() );
for( int i = 0; i < picture.width(); i++ )for( int j = 0; j < picture.height(); j++ )rotated.set( picture.height() - j - 1, i, picture.get( i, j ) );
Inheritance
Inheritance
The idea of inheritance is to take one class and generate a child class
This child class has everything that the parent class has (members and methods)
But, you can also add more functionality to the child
The child can be considered to be a specialized version of the parent
Code reuse
The key idea behind inheritance is safe code reuse
You can use old code that was designed to, say, sort lists of Vehicles, and apply that code to lists of Cars
All that you have to do is make sure that Car is a subclass (or child class) of Vehicle
Subclass relationship
Java respects the subclass relationship
If you have a Vehicle reference, you can store a Car object in that reference
A subclass (in this case a Car) is a more specific version of the superclass (Vehicle)
For this reason, you can use a Car anywhere you can use a Vehicle
You cannot use a Vehicle anywhere you would use a Car
Extending a superclass We use the extends keyword to create a
subclass from a superclass
A Car can do everything that a Vehicle can, plus more
public class Car extends Vehicle {private String model;public Car(String s) { model = s; }
public String getModel() { return model; }
public void startEngine() {System.out.println("Vrooooom!");}
}
Files
Files in Java
It is possible to read and write individual pieces of data to a text file
Files are great because they exist after the program is done
Reading and writing to a file is very similar to reading and writing to the command line (using Scanner and System.out)
Reading
Reading from a text file uses Scanner, just like reading from the command line
We just have to create a new File object that gives the file we want to read from
This code will read from some file called input.txt, as if someone were typing its contents into the command line
Scanner in = new Scanner(new File("input.txt"));
Writing
Java loves objects If you want to write to a file, you've got
to create a PrintWriter object, based on a FileOutputStream object (which takes the file name as a parameter)
Once you've got a PrintWriter, you can use it just like System.out
PrintWriter out = new PrintWriter(new FileOutputStream ("output.txt"));
Throw them 'bows! Using Scanner or PrintWriter to open a file
for reading or writing can throw an exception The easiest way to fix the problem is to
throw the exception up to the next level We do this by putting a throws FileNotFoundException on the declaration of main() (or whatever method we're in)
public static void main(String[] args) throws FileNotFoundException{
Scanner in = new Scanner(new File("input.txt"));
Shut 'em down! Unlike the command line, you should really
close files when you're done reading from them If you forget, it's okay: Java will automatically
close them when your program quits But, for situations where you're accessing
multiple files, it may be important to close themScanner in = new Scanner(new File("input.txt"));PrintWriter out = new PrintWriter(new FileOutputStream ("output.txt"));
//do stuffin.close();out.close();
Libraries You Should Know
String
Return type Name Job
int length() Find the length of the String
char charAt(int i) Give the char at index i (starting from 0)
boolean equals(String s)Returns true if s contains
exactly the same characters, false otherwise
int compareTo(String s)
Returns a negative number if the String comes before s in
the alphabet, a positive number if the String comes after s in the alphabet, and 0 if they are
identical
String substring(int a, int b)
Returns the substring of the String that starts at index a and goes up to but does not
include index b
Math
Return type
Name Job
double sin( double theta ) Find the sine of angle theta
double cos( double theta ) Find the cosine of angle theta
double tan( double theta ) Find the tangent of angle theta
double exp( double a ) Raise e to the power of a (ea)
double log( double a ) Find the natural log of adouble pow( double a, double b ) Raise a to the power of b
(ab)long round( double a ) Round a to the nearest
integerdouble random() Create a random number
in [0, 1)double sqrt( double a ) Find the square root of a
Scanner
Return Type Method Useint nextInt() Read in the next int
double nextDouble() Read in the next double
String next() Read in the next String
StdDraw drawing methods
Return Type
Method Use
void line(double x0, double y0, double x1, double y1)
Draw a line from (x0,y0) to (x1,y1)
void point(double x, double y) Draw a point at (x,y)void circle(double x, double
y, double r)Draw a circle centered at (x,y) with radius r
void filledCircle(double x, double y, double r)
Draw a filled circle centered at (x,y) with radius r
void square(double x, double y, double r)
Draw a square centered at (x,y) with edges 2r
void filledSquare(double x, double y, double r)
Draw a filled square centered at (x,y) with edges 2r
void setPenColor(Color c) Start drawing with color c
StdDraw control methods
Return Type Method Use
void setXscale(double x0, double x1) Set the x scalevoid setYscale(double y0, double y1) Set the y scalevoid setPenRadius(double r) Set the pen radiusvoid setCanvasSize(int w, int h) Set canvas sizevoid clear() Clear canvas to
whitevoid clear(Color c) Clear canvas to
color cvoid show(int delay) Delay for delay
ms
StdAudio
Return Type Method Use
double[] read(String file) Read a WAV file into an array of doubles
void save(String file, double[] input)
Save an array of doubles (samples) into a WAV file
void play(String file) Play a WAV file
void play(double[] input) Play an array of doubles (samples)
Color
Return Type Method Use
Color(int r, int g, int b)Creates a new color with r, g, and b as the red, green, and blue values
int getRed() Get the red color component
int getGreen() Get the green color component
int getBlue() Get the blue color component
Picture
Return Type
Method Use
Picture(String file) Creates a Picture from a file
Picture(int w, int h) Create a blank Picture with width w and height h
int width() Return the width of the imageint height() Return the height of the image
Color get(int i, int j) Return the Color of the pixel at (i,j)
void set(int i, int j, Color c) Set the Color of the pixel at (i,j) to c
void show() Display the imagevoid save(String file) Save the Picture to a file
Lab 15
Upcoming
Next time…
There is no next time!
Reminders
Finish Project 5! Due tonight before midnight
Study for Final Exam 2:30 - 5:30pm, Thursday, 12/10/2015
(CS121B) 11:00am - 2:00pm, Monday,
12/07/2015 (CS121C)