CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation...

53
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: [email protected]

Transcript of CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation...

Page 1: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

CS 112 Introduction to Programming

User-Defined Data Types: Using static to hide OOP;

Encapsulation

Yang (Richard) YangComputer Science Department

Yale University308A Watson, Phone: 432-6400

Email: [email protected]

Page 2: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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

Page 3: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

3

Recap: OOP

Identify objects that are part of the problem domain or solution

An object includes both state and behaviors

Focus on external behaviors (more shortly)

Page 4: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

Recap: Side-by-Side Comparison

4

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(){ ... }}

Function-oriented Object-oriented

Page 5: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

Static Math.random() method vs Random Objects

5

Page 6: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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

Page 7: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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.

Page 8: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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 timeint randomNumber = rand.nextInt(10); // 0-9

Method name Description

Random(long seed) Create a random number using a seed (R0)

Random() Create a random number using a seed derived from time

setSeed(seed) Initialize the random number generator

nextInt(<max>) 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?

Page 9: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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;

Page 10: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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

Page 11: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

11

How May Math.random()be Implemented?

public class Math {

static Random rand;

public static double random() { if (rand == null) rand = new Random(); return rand.nextDouble(); }..}

A static variable, also called a singleton.

Page 12: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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 2

client 3

client 1

client 2

client 3

Page 13: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

StdDraw vs DrawingPanel

13

Page 14: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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

Page 15: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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

Page 16: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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 getGraphics

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

Page 17: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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+

Page 18: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

Some Graphics Methods

Method name Description

g.setColor(Color); set Graphics to paint any following shapes in the given color

g.drawLine(x1, y1, x2, y2); line between points (x1, y1), (x2, y2)

g.drawOval(x, y, width, height); outline largest oval that fits in a box of size width * height with top-left at (x, y)

g.drawRect(x, y, width, height); outline of rectangle of sizewidth * height with top-left at (x, y)

g.drawString(text, x, y); text with bottom-left at (x, y)

g.fillOval(x, y, width, height); fill largest oval that fits in a box of size width * height with top-left at (x, y)

g.fillRect(x, y, width, height); fill rectangle of size width * height with top-left at (x, y)

http://download.oracle.com/javase/6/docs/api/java/awt/Graphics.htmlSee SimplePanels.java

Page 19: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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 programSee SimplePanels.java

Page 20: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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?

Page 21: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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.

double real = re + b.re; double imag = im + b.im; return new Complex(real, imag);}

Page 22: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

22

Complex.javapublic 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

Page 23: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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.

Page 24: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

24

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 = 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 TestClienta = 3.0 + 4.0ib = -2.0 + 3.0ic = 2.0 + 3.0id = 3.0 + 10.0i

Page 25: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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/

Page 26: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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.

z = 1 + i not in Mandelbrot setz = -1/2 is in Mandelbrot set

-1/2 + 0i0

-1/4 + 0i1

-7/16 + 0i2

-79/256 + 0i3

-26527/65536 + 0i4

-1443801919/4294967296 + 0i

zt

5

t

1 + i0

1 + 3i1

-7 + 7i2

1 - 97i3

-9407 – 193i4

88454401 + 3631103i

zt

5

t

Page 27: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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.

Page 28: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

28

Testing Point in Mandelbrot Set

Our Mandelbrot test: Returns the number of iterations to check if z0 isin 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 = z2 + z0

Page 29: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

29

Plotting Mandelbrot Set

Practical issues. Cannot plot infinitely many points.

Display technique. User specifies center, size Program maps the points on the

N-by-N drawing panel to center, size

xc+ yci

(xc-size/2) + (yc-size/2) i

Each grid has length size/N

Page 30: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

30

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 } // end of for} (0, 0) is upper left

Page 31: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

31

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

Page 32: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

32

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

Page 33: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

Picture Data Type

Raster graphics. Basis for image processing.

Set of values. 2D array of Color objects (pixels).

API.

Page 34: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

34

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 } // end of for}

scale to screen coordinates

(0, 0) is upper left

Page 35: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

35

Mandelbrot Set

% java ColorMandelbrot –.5 0 2

Plot the Mandelbrot set in color using a color mapping table.

Page 36: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

36

Mandelbrot Set

% java ColorMandelbrot –.5 0 2

Plot the Mandelbrot set in color using a color mapping table.

Page 37: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

37

Page 38: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

38

Mandelbrot Set

(-1.5, -1)

Page 39: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

39

Mandelbrot Set

See videohttp://www.youtube.com/watch?v=cXM9J77StL0

Page 40: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

40

Outline

Admin and recap Defining classes

o Motivation and basic syntaxo Examples The encapsulation principle

Page 41: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

41

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

Page 42: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

42

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

ClientClient Methods

Data/stateClient should not see the internal state or

behaviors

Client can see only the external API

(state and behaviors)

Page 43: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

Encapsulation Analogy

Implementation and client need to agree on API ahead of time.

Client API Implementation

client needs to know how to use API

implementation needs to knowwhat API to implement

Page 44: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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

Page 45: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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

Page 46: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

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 polar

coordinates (r, θ) so long you provide translation in the interface, clients will not see difference.

Page 47: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

47

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

Page 48: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

48

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.

Page 49: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

49

Using Access Modifiers to Implement Encapsulation: MethodsOnly service methods should be

made public

Support or helper methods created simply to assist service methods should be declared private

Page 50: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

50

The Effects of Public and Private Accessibility

violateEncapsulationUse Caution

enforceencapsulation

provide services to clients

support othermethods in theclass

public private

variables

methods

Page 51: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

51

Examples: Set the Access Modifiers

Coin

Ball

BankAccount

Point

Page 52: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

52

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 nameclass name

attributesattributes

methodsmethods

Page 53: CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.

Encapsulated data types. Don't touch data and do whatever you want. Instead, ask object to manipulate its data.

Lesson. Limiting scope makes programs easier to maintain and understand.

Adele GoldbergFormer president of ACMCo-developed Smalltalk

Ask, Don't Touch

"principle of least privilege"

"Ask, don't touch."