1 / 53

CS 112 Introduction to Programming

Learn how to use static methods to hide object-oriented programming concepts and explore encapsulation in Java. Topics discussed include random number generation, the Random class, Math.random(), and the advantages and issues of using Math.random().

Download Presentation

CS 112 Introduction to Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP;Encapsulation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

  2. Admin • PS7 (GuitarHero) • Walkthrough Tuesday at 8 pm • Project • Please start to work on teaming as soon as you can • If you need to find a partner, please send me a note so that we can arrange meetings at office hours

  3. Recap: OOP • Identify objectsthat are part of the problem domain or solution • An object includes both state and behaviors • Focus on external behaviors (more shortly)

  4. Recap: Side-by-Side Comparison Object-oriented Function-oriented public class DrawRocket{ public static void main(String args[]){ for (int size = 3; size < 10; size++){ drawRocket(size); } } public static void drawRocket(int scale){ printCap(scale); ... } ... public static void printCap(int scale){ ... } } public class RocketDrawing { public static void main(String args[]){ for (int size = 3; size < 10; size++){ Rocket curRocket = new Rocket(size); curRocket.draw(); } } } public class Rocket{ public int rocketSize; public Rocket(int rocketSize){ this.rocketSize = rocketSize; } public void drawRocket(){ printCap(); ... } ... public void printCap(){ ... } }

  5. Static Math.random() method vs Random Objects

  6. Math.random() Design • public static double random() • Returns a random number between 0 and 1 • Most static methods that we encountered are deterministic methods: given the same input parameter, gives the same output • But the random() method cannot be, i.e., it is non-deterministic

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

  8. 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 intrandomNumber = rand.nextInt(10); // 0-9 Q: What is the state of a Random object?

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

  10. Math.random() • public static double random() • When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random() • This new pseudorandom-number generator is used thereafter for all calls to this method. • http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random()

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

  12. Advantage and Issue of Using Math.random() • Advantage • Hide object-oriented programming, simplifying programming • Issue • A single Random object: Every request for a random number is handled by one single random object, creating a bottleneck client 1 client 1 client 2 client 2 client 3 client 3

  13. StdDraw vs DrawingPanel

  14. DrawingPanel Developed for the Back to Basics Textbook, using an OOP approach. Two key classes: • DrawingPanel: A window on the screen. • Not part of Java; provided by the textbook. • Graphics: A "pen" to draw shapes and lines on a window. • from Java standard class library

  15. DrawingPanel A "Canvas" object that represents windows/drawing surfaces • To create a window: DrawingPanel name = new DrawingPanel(width, height); Example: DrawingPanel panel = new DrawingPanel(300, 200); See SimplePanels.java

  16. Graphics • DrawingPanel draws shapes / lines /characters /imagines using another object of type Graphics. • Graphics: Your painting toolset: "Pen" or "paint brush" objects to draw lines and shapes; fonts for character, … • Access it by calling getGraphicson a DrawingPanel object. Graphics g = panel.getGraphics(); • Draw shapes by calling methodson the Graphics object. g.fillRect(10, 30, 60, 35); g.fillOval(80, 40, 50, 70);

  17. Graphics Coordinate System • Each (x, y) position is a pixel ("picture element"). • Position (0, 0) is at the window's top-left corner. • x increases rightward and the y increases downward. • A rectangle from (0, 0) to (200, 100) looks like this: (0, 0) x+ (200, 100) y+

  18. Some Graphics Methods See SimplePanels.java http://download.oracle.com/javase/6/docs/api/java/awt/Graphics.html

  19. Benefit and Issue of StdDraw • StdDraw • Similar to Math.random() creating a single Random object, StdDraw creates a single drawing object • Benefit • 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 • Potential issue • Only 1 drawing surface in your program See SimplePanels.java

  20. Recap: The Complex Class: Design Question public class Complex { double re; double im; public Complex(double real,double imag) { re = real; im = imag; } public ?? plus(Complex b) { … } … • How to design the plus instance method?

  21. Recap: The Consistency (Familiarity) Design Principle • Suppose a, b, and c are standard numbers (Complex numbers are numbers after all) • What does a + b (think a.+(b) ) do? • Returns the value of a + b so that we can write a + b + c; the value of a is not changed. public Complex plus(Complex b) { double real = re + b.re; double imag = im + b.im; returnnew Complex(real,imag); }

  22. 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"; } publicdouble abs() { return Math.sqrt(re*re + im*im); } public Complex plus(Complex b) { double real = re + b.re; double imag = im + b.im; returnnew Complex(real,imag); } public Complex times(Complex b) { double real = re * b.re – im * b.im; double imag = re * b.im + im * b.re; returnnew Complex(real,imag); } } instance variables constructor refers to b's instance variable creates a Complex object,and returns a reference to it methods

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

  24. A Simple Client publicstaticvoid main(String[] args) { Complex a =new Complex( 3.0,4.0); Complex b =new Complex(-2.0,3.0); Complex c =new Complex( 2.0,3.0); Complex d = a.plus(b).plus(c); System.out.println("a = "+ a.toString() ); System.out.println("b = "+ b.toString() ); System.out.println("c = "+ c.toString() ); System.out.println(“d = "+ d.toString() ); } % java TestClient a = 3.0 + 4.0i b = -2.0 + 3.0i c = 2.0 + 3.0i d = 3.0 + 10.0i

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

  26. A Complex Client: Mandelbrot Set Mandelbrot set. Is complex number z0 in the set? • Iterate zt+ 1 = (zt)2 + z0. • If |zt| diverges to infinity, then z0 is not in set;otherwise z0 is in set. t zt t zt 0 -1/2 + 0i 0 1 + i 1 -1/4 + 0i 1 1 + 3i 2 -7/16 + 0i 2 -7 + 7i 3 -79/256 + 0i 3 1 - 97i 4 -26527/65536 + 0i 4 -9407 – 193i 5 -1443801919/4294967296 + 0i 5 88454401 + 3631103i z = -1/2 is in Mandelbrot set z = 1 + i not in Mandelbrot set

  27. Testing Point in Mandelbrot Set Practical issues. • Cannot iterate infinitely many times. Approximate solution. • Fact: if |zt| > 2 for any t, then z not in Mandelbrot set. • Pseudo-fact: if |z255| 2 then z "likely" in Mandelbrot set.

  28. Testing Point in Mandelbrot Set Our Mandelbrot test: Returns the number of iterations to check if z0 isin Mandelbrot public staticintmand(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 = z2 + z0

  29. Plotting Mandelbrot Set Practical issues. • Cannot plot infinitely many points. Display technique. • User specifies center, size • Program maps the points on theN-by-Ndrawing panel to center, size xc+ yci Each grid has length size/N (xc-size/2) + (yc-size/2) i

  30. Plotting Mandelbrot Set (DrawingPanel) Plot the Mandelbrot set in gray scale. publicstaticvoid 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 } // end of for } (0, 0) is upper left

  31. Mandelbrot Set % java MandelbrotDrawingPanel –.5 0 2 % java MandelbrotDrawingPanel .1045 -.637 .01

  32. Mandelbrot Set % java MandelbrotDrawingPanel –.5 0 2 % java MandelbrotDrawingPanel .1045 -.637 .01

  33. Picture Data Type • Raster graphics. Basis for image processing. • Set of values. 2D array of Colorobjects (pixels). • API.

  34. Plotting Mandelbrot Set (Picture) Plot the Mandelbrot set in gray scale. publicstaticvoid main(String[]args) { double xc =Double.parseDouble(args[0]); doubleyc=Double.parseDouble(args[1]); double size =Double.parseDouble(args[2]); Picture pic = new Picture(N, N); // NxN picture for(inti=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 } // end of for } scale to screen coordinates (0, 0) is upper left

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

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

  37. Mandelbrot Set (-1.5, -1)

  38. Mandelbrot Set • See video • http://www.youtube.com/watch?v=cXM9J77StL0

  39. Outline • Admin and recap • Defining classes • Motivation and basic syntax • Examples • The encapsulation principle

  40. Two Views of an Object • You can take one of two views of an object: • external (API) - the interaction of the object with its clients • internal (implementation) - the structure of its data, the algorithms used by its methods

  41. The Encapsulation Principle • An object should be an encapsulated entity (a black box), providing an API (i.e., a set of external visible state and services/behaviors) • The user, or client, of an object should not be aware of the internal representation of state or details of algorithms Methods Client Client can see only the external API (state and behaviors) Data/state Client should not see the internal state or behaviors

  42. Encapsulation Analogy Client API Implementation client needs to know how to use API implementation needs to knowwhat API to implement Implementation and client need to agree on API ahead of time.

  43. Encapsulation Analogy • You don't understand the inner details of iPhone, and you don't need to. • Apple does not want to commit to any internal details so that Apple can continuously update the internal

  44. Examples • What are some risks of allowing others to view/access the internal state of a class? • The Coin class • The Ball class • The Point class • The BankAccount class

  45. Why Encapsulating Data • Consistency: so that we make it impossible for others to "reach in" and directly alter another object's state • Protect object from unwanted access • Example: Can't fraudulently increase an BankAccount balance. • Maintain state invariants • Example: Only allow BankAccounts with non-negative balance. • Example: Only allow Dates with a month from 1-12. • Flexibility: so that you can change the state representation later without worrying about breaking others’ code • Example: Point could be rewritten in polarcoordinates (r, θ) so long you provide translation in the interface, clients will not see difference.

  46. Accomplish Encapsulation: Access Modifiers • In Java, we accomplish encapsulation through the appropriate use of access modifiers • An access modifier is a Java reserved word that specifies the accessibility of a method, data field, or class • we will discuss two access modifiers: public, private • we will discuss the other modifier (protected) later

  47. The public and private Access Modifiers • 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 • Members without an access modifier: default private accessibility, i.e., accessible in the same package; otherwise, not accessible.

  48. Using Access Modifiers to Implement Encapsulation: Methods • Only service methods should be made public • Support or helper methods created simply to assist service methods should be declared private

  49. The Effects of Public and Private Accessibility private public violate Encapsulation Use Caution enforce encapsulation variables provide services to clients support other methods in the class methods

More Related