CS 112 Introduction to Programming Design Good Classes: Visualization and OOP Analysis Yang (Richard) Yang Computer Science Department Yale University.

Slides:



Advertisements
Similar presentations
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Advertisements

Modular Programming With Functions
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
1 Various Methods of Populating Arrays Randomly generated integers.
Building Java Programs
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Building Java Programs Chapter 5
Road Map Introduction to object oriented programming. Classes
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Class Design Lecture 9, Mon Jan
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Class Design Lecture 6, Tue Jan
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
1 Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1, 5.6.
MIT AITI 2003 Lecture 7 Class and Object - Part I.
Designing Data Types. 2 Object Oriented Programming Procedural programming. [verb-oriented] n Tell the computer to do this. n Tell the computer to do.
3.3 Designing Data Types Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · September.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Chapter 3 Introduction to Collections – Stacks Modified
CSC 212 Object-Oriented Programming and Java Part 1.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
1 Introduction Modules  Most computer programs solve much larger problem than the examples in last sessions.  The problem is more manageable and easy.
CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
Random numbers. 2 The Random class A Random object generates pseudo-random numbers. –Class Random is found in the java.util package. import java.util.*;
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
CS 112 Introduction to Programming Graphics; Animation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
1 Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1, 5.6.
CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.
Chapter 4 Introduction to Classes, Objects, Methods and strings
CS 112 Introduction to Programming Design Good Classes: Encapsulation and OOP Analysis Yang (Richard) Yang Computer Science Department Yale University.
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
CS 112 Introduction to Programming Variable Scoping; Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Classes Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Classes. Preparation Scene so far has been background material and experience –Computing systems and problem solving –Variables –Types –Input and output.
3.2 Creating Data Types Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · January.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-2: Random Numbers; Type boolean reading: , 5.6.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
Arrays and Array Lists CS 21a. Problem 1: Reversing Input Problem: Read in three numbers and then print out the numbers in reverse order Straightforward.
Unified Modeling Language (UML)
CS 112 Introduction to Programming Loop Examples; Variable Scoping; Nested Loops; Yang (Richard) Yang Computer Science Department Yale University 208A.
CS 112 Introduction to Programming Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
CS 112 Introduction to Programming Java Graphics Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
CS 112 Introduction to Programming Object Relationship Analysis: Composition, Association, Inheritance Yang (Richard) Yang Computer Science Department.
CS 112 Introduction to Programming Class Inheritance Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
1 Building Java Programs Chapter 5 Lecture 11: Random Numbers reading: 5.1, 5.6.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs

Classes A class is a blueprint of an object
Chapter 4: Writing Classes
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Object Based Programming
Building Java Programs
Building Java Programs
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Building Java Programs
Building Java Programs
Presentation transcript:

CS 112 Introduction to Programming Design Good Classes: Visualization and OOP Analysis Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:

2 Admin  PS7 m Questions? m If you want bonus points by performing a GuitarHero, please let me know soon  Project teaming due tonight m Please use the Google spreadsheet to add your team members; if you have a rough idea of your project, please write down, as it helps us in matching smq7YL_gBLSJFH7I2Ca3EiAdBdsDCVY4M/edit?usp=sha ring

3 Recap: The Encapsulation Principle Client Methods Data/state/ behaviors Client should not see the internal state or behaviors Client can see only the external API Benefits  Consistency: so that it is impossible for others to "reach in" and directly alter another object's state  Flexibility: so that you can change the state representation or impl later without worrying about breaking others’code

 Encapsulated data types. m Don't touch data and do whatever you want. m Instead, ask object to manipulate its data.  Lesson. Limiting scope makes programs easier to maintain and understand. Ask, Don't Touch "principle of least privilege" "Ask, don't touch."

5 Recap: Encapsulation/How r access modifiers enforce encapsulation  public members (data and methods: can be accessed from anywhere  private members: can be accessed from a method defined in the same class m Members without an access modifier: default private accessibility, i.e., accessible in the same package; otherwise, not accessible.

6 Class Diagram Coin - face : int + flip() : void + isHeads() : boolean + toString() : String Above is a class diagram representing the Coin class. “-” indicates private data or method “+” indicates public data or method class name attributes methods

7 Recap: StdDraw vs DrawingPanel  StdDraw: a Non-OO design m Benefits Hides OOP programming complexity (No objects) Simplifies programming by converting the native Java coordinate system (up-side down) to a more intuitive coordinate system Adds additional methods such as square, point m Potential issue Only 1 drawing surface in your program  DrawingPanel m OO design allowing multiple panels

8 Outline  Admin and recap  Defining classes o Motivation and basic syntax o Simple examples o The encapsulation principle o OOP examples o DrawingPanel objects vs StdDraw  Random objects vs Math.random

Static Math.random() method vs Random Objects 9

10 Math.random() Design r public static double random() m Returns a random number between 0 and 1 r Most static methods that we encountered are deterministic methods m deterministic method: given the same input parameter, gives the same output  But the random() method cannot be (why?)

11 A Little Peek into Random Number Generation r The random numbers generated by Java are actually pseudo-random numbers  Suppose you get a random number R n, the next time you call it to get R n+1, it returns: R n+1 = R n * it then converts to the right range to you ! r This method is proposed by D. H. Lehmer m in mathematical jargon, Java uses a type of linear congruential pseudorandom number generator r Implication: the previously returned random number must be remembered.

The Random class  A Random object generates random numbers as preceding slide  Class Random is found in the java.util package. import java.util.Random;  Example: Random rand = new Random(); // Default, seed by time int randomNumber = rand.nextInt(10); // 0-9 Method nameDescription Random(long seed) Create a random number using a seed (R 0 ) Random() Create a random number using a seed derived from time setSeed(seed) Initialize the random number generator nextInt( ) Returns a random integer in the range [0, max) in other words, 0 to max-1 inclusive nextDouble() Returns a random real number in [0.0, 1.0) Q: What is the state of a Random object?

Using Random Numbers r Example: to get a random number from 1 to 20 int n = rand.nextInt(20) + 1; // 1-20 inclusive r To get a number in arbitrary range [min, max] inclusive:.nextInt( ) + Where is ( ) m Example: A random integer between 4 and 10 inclusive: int n = rand.nextInt(7) + 4;

14 Math.random() r public static double random() m When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random() m This new pseudorandom-number generator is used thereafter for all calls to this method. r va/lang/Math.html#random()

15 How May Math.random() be Implemented? public class Math { private static Random rand; public static double random() { if (rand == null) rand = new Random(); return rand.nextDouble(); }.. } A static variable, also called a singleton. A delegation implementation pattern.

16 Advantage and Issue of Using Math.random() r Advantage m Hide object-oriented programming, simplifying programming (shorter program, no need to know seeds) r Issue  A single Random object: Every request for a random number is handled by one single random object, creating a bottleneck client 1 client 2 client 3 client 1 client 2 client 3

17 Outline  Admin and recap  Defining classes o Motivation and basic syntax o Simple examples o The encapsulation principle o OOP examples o DrawingPanel objects vs StdDraw o Random objects vs Math.random  Complex numbers and fractal graphics

18 Complex Numbers r A complex number (a + bi) is a quintessential mathematical abstraction m (a + bi) + (c + di) = a + c + (b + d) i m (a + bi) x (c + di) = ac - bd + (ad + bc)i r A main power of complex numbers comes from Euler’s formula a = 3 + 4i, b = i a + b = 1 + 7i a  b = i | a | = 5

19 Complex Numbers are Widely Used r Control theory and Laplace transforms r Quantum mechanics and Hilbert spaces r Fractals r Signal processing and Fourier analysis Antennas

20 A Complex Class r Design questions: m State: what field(s) do we need to represent the state of a complex number? Design 1 –re, a number representing the real part –im, a number representing the imaginary part Design 2 –r, a number representing the distance to origin –theta, a number representing the angle

21 A Complex Class r Design questions: m Behaviors: what are some common behaviors of a complex number? a Complex constructor, to set up the object A abs method, to return the distance (magnitude) a toString method, to return a string description of a complex number Mathematical operations such as +, -, * –a plus method to add current complex number with another complex number –a times method to multiply current complex number with another complex number –…–…

22 The Complex Class: Design Question public class Complex { private double re; private double im; public Complex(double real, double imag) { re = real; im = imag; } public ?? plus(Complex b) { … } … -What is the return type of plus? -Should plus change the state of the number, e.g., Complex c1 = new Complex(1, 1); Complex c2 = new Complex(2, 1); c1.plus(c2); // c1 changes to (3, 2)

23 The Consistency (Familiarity) Design Principle r Suppose a, b, and c are standard numbers (Complex numbers are numbers after all) m Does a + b (think a.+(b) ) change a? no m What is the return of a + b (think a.+(b))? The value of a + b so that we can write a + b + c r State (no)change and return type of plus public Complex plus(Complex b) { double real = re + b.re; double imag = im + b.im; return new Complex(real, imag); }

24 Complex.java public class Complex { double re; double im; public Complex(double real, double imag) { re = real; im = imag; } public String toString() { return re + " + " + im + "i"; } public double abs() { return Math.sqrt(re*re + im*im); } public Complex plus(Complex b) { double real = re + b.re; double imag = im + b.im; return new Complex(real, imag); } public Complex times(Complex b) { double real = re * b.re – im * b.im; double imag = re * b.im + im * b.re; return new Complex(real, imag); } constructor instance variables methods creates a Complex object, and returns a reference to it refers to b's instance variable

Immutability: Advantages and Disadvantages r Immutable data type. Object's state does not change once constructed. m Complex is an example of Immutable objects. String defined by Java is another example. r Advantages. m Avoid aliasing bugs. m Makes program easier to debug. m Limits scope of code that can change values. m Pass objects around without worrying about modification. r Disadvantage. New object must be created for every value.

26 A Simple Client public static void main(String[] args) { Complex a = new Complex( 3.0, 4.0); Complex b = new Complex(-2.0, 3.0); Complex c = a.times(b); System.out.println("a = " + a.toString() ); System.out.println("b = " + b.toString() ); System.out.println("c = " + c.toString() ); } % java TestClient a = i b = i c = i

27 A Complex Client: Mandelbrot Set r Mandelbrot set. A set of complex numbers.  Plot. Plot (x, y) black if z = x + y i is in the set, and white otherwise. r Can be used to model complex rugged shapes such as uneven clouds, contours of mountains, winding riverbeds, arts, … r No simple formula describes which complex numbers are in set. - Instead, described using an algorithm.

28 A Complex Client: Mandelbrot Set Mandelbrot set. Is complex number z 0 in the set? Iterate z t + 1 = (z t ) 2 + z 0. If | z t | diverges to infinity, then z 0 is not in set; otherwise z 0 is in set. z = 1 + i not in Mandelbrot set z = -1/2 is in Mandelbrot set -1/2 + 0i0 -1/4 + 0i1 -7/16 + 0i2 -79/ i / i / i ztzt 5 t 1 + i i i i – 193i i ztzt 5 t

29 Testing Point in Mandelbrot Set Practical issues. n Cannot iterate infinitely many times. Approximate solution. Fact: if | z t | > 2 for any t, then z not in Mandelbrot set. Pseudo-fact: if | z 255 | < 2 then z "likely" in Mandelbrot set.

30 Testing Point in Mandelbrot Set Our Mandelbrot test: Returns the number of iterations to check if z0 is in Mandelbrot public static int mand(Complex z0) { final int max = 255; Complex z = z0; for (int t = 0; t < max; t++) { if (z.abs() > 2.0) return t; z = z.times(z).plus(z0); } return max; } z = z 2 + z 0

31 Plotting Mandelbrot Set Practical issues. n Cannot plot infinitely many points. Display technique. n User specifies center, size Program maps the points on the N -by- N drawing panel to center, size x c + y c i (x c -size/2) + (y c -size/2) i Each grid has length size/N

32 Plotting Mandelbrot Set (DrawingPanel) Plot the Mandelbrot set in gray scale. public static void main(String[] args) { double xc = Double.parseDouble(args[0]); double yc = Double.parseDouble(args[1]); double size = Double.parseDouble(args[2]); DrawingPanel panel = new DrawingPanel(N, N); Graphics g = panel.getGrahics(); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { double x0 = xc - size/2 + size*i/N; double y0 = yc - size/2 + size*j/N; Complex z0 = new Complex(x0, y0); int gray = mand(z0); Color color = new Color(gray, gray, gray); g.setColor( color ); g.drawLine(i, N-1-j, i, N – 1 - j); } // end of for } (0, 0) is upper left

33 Mandelbrot Set % java MandelbrotDrawingPanel –.5 0 2% java MandelbrotDrawingPanel

34 Mandelbrot Set % java MandelbrotDrawingPanel –.5 0 2% java MandelbrotDrawingPanel

35 Mandelbrot Set % java ColorMandelbrot – Plot the Mandelbrot set in color using a color mapping table.

36 Mandelbrot Set % java ColorMandelbrot – Plot the Mandelbrot set in color using a color mapping table.

37

38 Mandelbrot Set (-1.5, -1)

39 Mandelbrot Set  See video 77StL0

Picture Data Type r Raster graphics. Basis for image processing.  Set of values. 2D array of Color objects (pixels). r API.

41 Plotting Mandelbrot Set (Picture) Plot the Mandelbrot set in gray scale. public static void main(String[] args) { double xc = Double.parseDouble(args[0]); double yc = Double.parseDouble(args[1]); double size = Double.parseDouble(args[2]); Picture pic = new Picture(N, N); // NxN picture for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { double x0 = xc - size/2 + size*i/N; double y0 = yc - size/2 + size*j/N; Complex z0 = new Complex(x0, y0); int gray = mand(z0); Color color = new Color(gray, gray, gray); pic.set(i, N-1-j, color); } // end of for } scale to screen coordinates (0, 0) is upper left