Week 15 – Friday.  Student Questions  Review up to Exam 2  Loops  Arrays  StdDraw  StdAudio  Static methods.

Slides:



Advertisements
Similar presentations
Python Objects and Classes
Advertisements

MATH 224 – Discrete Mathematics
1 Various Methods of Populating Arrays Randomly generated integers.
TOPIC 5 INTRODUCTION TO PICTURES 1 1 Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B.
Written by: Dr. JJ Shepherd
Week 12 - Wednesday.  What did we talk about last time?  Hunters and prey  Class variables  Big Oh notation.
Week 11 - Friday.  What did we talk about last time?  Object methods  Accessors  Mutators  Constructors  Defining classes.
Inheritance Inheritance Reserved word protected Reserved word super
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Week 11: Class Design 1.  Most classes are meant to be used more than once  This means that you have to think about what will be helpful for future.
Week 10: Objects and Classes 1.  There are two classifications of types in Java  Primitive types:  int  double  boolean  char  Object types: 
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 CS 177 Week 15 Recitation Slides Review. Announcements Final Exam on Sat. May 8th  PHY 112 from 8-10 AM Complete your online review of your classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
CS0007: Introduction to Computer Programming Introduction to Arrays.
Games and Simulations O-O Programming in Java The Walker School
Java Unit 9: Arrays Declaring and Processing Arrays.
Week 10 - Monday.  What did we talk about last time?  Method overloading  Lab 9.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Week 14 - Monday.  What did we talk about last time?  Image manipulation  Inheritance.
Week 13 - Wednesday.  What did we talk about last time?  Color representation  Color class  Picture class.
Writing Classes (Chapter 4)
Week 2 - Monday.  What did we talk about last time?  Exceptions  Threads  OOP  Interfaces.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Week 6 - Wednesday.  What did we talk about last time?  Exam 1 post-mortem  Recursive running time.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Week 2 - Friday.  What did we talk about last time?  Using Scanner to get input  Basic math operations.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
Week 2 - Wednesday.  What did we talk about last time?  Running time  Big Oh notation.
1 ball, 2 ball, red ball, blue ball By Melissa Dalis Professor Susan Rodger Duke University June 2011.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Programming in Java CSCI-2220 Object Oriented Programming.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
Week 14 - Monday.  What did we talk about last time?  Inheritance.
Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions.
1 CS 177 Week 11 Recitation Slides Class Design/Custom Classes.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Week 13 - Wednesday.  What did we talk about last time?  Color representation  Color class  Picture class.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Week 12 - Friday.  What did we talk about last time?  Finished hunters and prey  Class variables  Constants  Class constants  Started Big Oh notation.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Week 12 - Wednesday.  What did we talk about last time?  Hunters and prey.
Written by: Dr. JJ Shepherd
Week 12 - Monday.  What did we talk about last time?  Defining classes  Class practice  Lab 11.
CS 5JA Introduction to Java Graphics One of the powerful things about Java is that there is.
Week 10 - Wednesday.  What did we talk about last time?  Method example  Roulette simulation  Types in Java.
Week 10 - Friday.  What did we talk about last time?  References and primitive types  Started review.
Week 10 - Monday.  What did we talk about last time?  Method overloading  Lab 9.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
Week 6 - Friday.  What did we talk about last time?  Loop examples.
Chapter 9 Introduction to Arrays Fundamentals of Java.
A High Flying Overview CS139 – Fall 2010 How far we have come.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Week 3 - Monday.  What did we talk about last time?  Using Scanner to get input  Basic math operations  Lab 2.
Week 4 - Friday CS221.
Week 13: Searching and Sorting
Week 13 - Monday CS 121.
Week 14 - Monday CS 121.
Week 14 - Wednesday CS 121.
CS 177 Week 15 Recitation Slides
Algorithm design and Analysis
Classes, Objects and Methods
Presentation transcript:

Week 15 – Friday

 Student Questions  Review up to Exam 2  Loops  Arrays  StdDraw  StdAudio  Static methods

 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; Eggplant aubergine; DumpTruck truck1; Idea thought; aubergine truck1thought

 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

 You are already familiar with calling methods on String s  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' String s = new String("Help me!"); char c = s.charAt(3); //c gets 'p'

 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 ham double weight = h.getWeight(); //gets current ham weight Ham h = new Ham(3.2); h.bite(); //takes bite out of ham double weight = h.getWeight(); //gets current ham weight

 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!"); else System.out.println("Different!"); if( s1.equals( s2 ) ) System.out.println("Same!"); else System.out.println("Different!"); String s1 = new String("identical"); String s2 = new String("identical"); if( s1 == s2 ) System.out.println("Same!"); else System.out.println("Different!"); if( s1.equals( s2 ) ) System.out.println("Same!"); else System.out.println("Different!");

 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

public class Name { private int member1; private double member2; private Hedgehog member3; public Name() { … } public int method1( double x ){ … } Class definition Member declarations Constructor definition Method definition

 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 world public class Point { private double x; // member variable private double y; // member variable } public class Point { private double x; // member variable private double y; // member variable }

 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 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 are a special kind of method  They allow you to customize an object with particular attributes when it is created public class Point { private double x; // member variable private double y; // member variable public Point( double newX, double newY ) { //constructor x = newX; y = newY; } public class Point { private double x; // member variable private double y; // member variable public Point( double newX, double newY ) { //constructor x = newX; y = newY; }

 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 x return x; } public double getY() { //accessor for y return y; } public double getX() { //accessor for x return x; } public double getY() { //accessor for y return y; }

 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 x x = newX; } public void setY( double newY ) { //mutator for y y = newY; } public void setX( double newX ) { //mutator for x x = newX; } public void setY( double newY ) { //mutator for y y = newY; }

 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; } } 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 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

 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

 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  Asymptotic We focus on the behavior as the input size gets larger and larger

 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

 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

 147n 3 + 2n 2 + 5n is O(n3)O(n3)  n n is O(2 n )  15n 2 + 6n + 7log n is O(n2)O(n2)  659n + nlog n is O(n log n)  Note: In CS, we use log 2 unless stated otherwise

 Here is a table of several different complexity measures, in ascending order, with their functions evaluated at n = 100 DescriptionBig Ohf(100) ConstantO(1)1 LogarithmicO(log n)6.64 LinearO(n)O(n)100 LinearithmicO(n log n) QuadraticO(n2)O(n2)10000 CubicO(n3)O(n3) ExponentialO(2 n )1.27 x FactorialO(n!)9.33 x

 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; } public static int find( int[] array, int number ) { for( int i = 0; i < array.length; i++ ) if( array[i] == number ) return i; return -1; }

 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 say Check the middle (Too high) Check the middle (Too low) Check the middle (Too low) Check the middle (Found it!) 37

 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 = 2 x n = 1

 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

 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; } 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; }

 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; } 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; }

 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 for Red, Green, and Blue

 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(); Color c = new Color(255,165,0); //orange int green = c.getGreen();

 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

012 0 A 1 B 2 C 3 D A 1 B 2 C 3 D OriginalMirrored

 Using the picture class, here is the code for mirroring Picture 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 ) ); Picture 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 ) );

012 0 A 1 B 2 C 3 D DCBA 1 2 Original Rotated

 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 ) ); 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 ) );

 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

 The key idea behind inheritance is safe code reuse  You can use old code that was designed to, say, sort lists of Vehicle s, and apply that code to lists of Car s  All that you have to do is make sure that Car is a subclass (or child class) of Vehicle

 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

 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!"); } 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!"); }

 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 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"));

 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"));

 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")); public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File("input.txt"));

 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 them Scanner in = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter(new FileOutputStream ("output.txt")); //do stuff in.close(); out.close(); Scanner in = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter(new FileOutputStream ("output.txt")); //do stuff in.close(); out.close();

Return type NameJob intlength() Find the length of the String charcharAt(int i) Give the char at index i (starting from 0) booleanequals(String s) Returns true if s contains exactly the same characters, false otherwise intcompareTo(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 Stringsubstring(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

Return typeNameJob doublesin( double theta ) Find the sine of angle theta doublecos( double theta ) Find the cosine of angle theta doubletan( double theta ) Find the tangent of angle theta doubleexp( double a ) Raise e to the power of a (e a ) doublelog( double a ) Find the natural log of a doublepow( double a, double b ) Raise a to the power of b (a b ) longround( double a ) Round a to the nearest integer doublerandom() Create a random number in [0, 1) doublesqrt( double a ) Find the square root of a

Return TypeMethodUse intnextInt() Read in the next int doublenextDouble() Read in the next double Stringnext() Read in the next String

Return TypeMethodUse voidline(double x0, double y0, double x1, double y1) Draw a line from (x0,y0) to (x1,y1) voidpoint(double x, double y) Draw a point at (x,y) voidcircle(double x, double y, double r) Draw a circle centered at (x,y) with radius r voidfilledCircle(double x, double y, double r) Draw a filled circle centered at (x,y) with radius r voidsquare(double x, double y, double r) Draw a square centered at (x,y) with edges 2r voidfilledSquare(double x, double y, double r) Draw a filled square centered at (x,y) with edges 2r voidsetPenColor(Color c) Start drawing with color c

Return Type MethodUse voidsetXscale(double x0, double x1) Set the x scale voidsetYscale(double y0, double y1) Set the y scale voidsetPenRadius(double r) Set the pen radius voidsetCanvasSize(int w, int h) Set canvas size voidclear() Clear canvas to white voidclear(Color c) Clear canvas to color c voidshow(int delay) Delay for delay ms

Return TypeMethodUse double[]read(String file) Read a WAV file into an array of double s void save(String file, double[] input) Save an array of double s (samples) into a WAV file voidplay(String file) Play a WAV file voidplay(double[] input) Play an array of double s (samples)

Return Type MethodUse Color(int r, int g, int b) Creates a new color with r, g, and b as the red, green, and blue values intgetRed() Get the red color component intgetGreen() Get the green color component intgetBlue() Get the blue color component

Return Type MethodUse Picture(String file) Creates a Picture from a file Picture(int w, int h) Create a blank Picture with width w and height h intwidth() Return the width of the image intheight() Return the height of the image Colorget(int i, int j) Return the Color of the pixel at ( i, j ) voidset(int i, int j, Color c) Set the Color of the pixel at ( i, j ) to c voidshow() Display the image voidsave(String file) Save the Picture to a file

 There is no next time!

 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)