Top Banner
CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: [email protected]
47

CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Jan 02, 2016

Download

Documents

Mark Jefferson
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

CS 112 Introduction to Programming

User-Defined Data Types: Examples

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: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

2

Admin

PS6 (Sukoku) questions Friday’s class

Page 3: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Recap: Design and Implementation Methodology: Procedural BasedDesign (goal oriented)

top-down stepwise goal-drivenmethod decomposition

methods designed are those needed for the current goal

verb driven

Program implementation and testing bottom-up

3

Page 4: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Recap: Design and Implementation Methodology: Object-Oriented Design

Identify objects that are part of the problem domain or solution

• Each object has state (variables)• Each object has behaviors (methods)

Often do not consider one specific goal, but rather a context

noun driven

4

Page 5: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Side-by-Side Comparison

5

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 draw(){ printCap(); ... } ... public void printCap(){ ... }}

Function-oriented Object-oriented

Page 6: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Recap: Class Definition Components

Variables fields (instance variables per object) static variables (shared by all objects)

Methods static methods (method usable with or without

object)• Can access only static variables

instance methods (can be used only on objects; can access both static and instance variables)

• Constructors• Accessors (do not change object state)• Mutators (modify object state)

6

Page 7: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Point class: Variables

public class Point {

// fields (instance variables, attributes) int x; int y;

// static variables shared by all objects static int numPoints = 0;

Page 8: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Point class: Constructors

public class Point { … // constructors public Point(int x, int y) { this.x = x; this.y = y; numPoints ++; // a shared variable to // keep track of all

// Points created. } public Point() { this(0, 0); }

Page 9: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Point class: Static Methods

public class Point { … // static methods: // cannot access any instance variables // because one may call Point.readpoint(input) // which has no implicit parameter public static Point readPoint(Scanner scan) { Point p = new Point(); p.x = scan.nextInt(); p.y = scan.nextInt(); return p; }

public static int totalPoints() { return numPoints; }

Page 10: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Point class: Instance Methods

// mutators public void translate(int dx, int dy) { x = x + dx; y = y + dy; } public void setLocation(int x, int y) { this.x = x; this.y = y; }

// accessors public double distanceFromOrigin() { return Math.sqrt(x * x + y * y); }

public String toString() { return "(" + x + ", " + y + ")“; }

public void draw() { StdDraw.filledCircle(x, y, 3); StdDraw.textLeft(x, y, toString() ); }}

Page 11: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Point class as blueprint

The class (blueprint) will describe how to create objects. Each object will contain its own data and methods.

Point classstate:

int x, ybehavior:

translate(int dx, int dy)draw()

Point object #1

state:x = 5, y = -2

behavior:translate(int dx, int dy)

draw()…

Point object #2

state:x = -245, y = 1897

behavior:translate(int dx, int dy)

draw()…

Point object #3

state:x = 18, y = 42

behavior:translate(int dx, int dy)

draw()…

Page 12: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

12

Outline

Admin and recap Defining classes

o Motivation and basic syntax Examples

Page 13: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Design and Implementation Methodology: Object-Oriented Design

Identify objects (nouns) and their behaviors

Often do not consider one specific goal, but rather a context

Often lead to more reusable, extensible software

13

Page 14: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

14

Example 1: A Coin Class

We define a Coin class to model a coin in heads-tails games

Design questions: State: what field(s) do we need to represent the state of a

coin?• face, an integer (or boolean) that represents the current face

Operations: what are some common behaviors/operations of a coin in a game context?

• a Coin constructor, to set up the object

• a isHeads method, to return if face is HEADS• a toString method, to return a string description of the current state

• a flip method, to flip the coin• Q: introduce a setFace() method?

See Coin.java, CountFlips.java, FlipRace.java

Page 15: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

15

Instance Data: The Two Coins in FlipRace

int face;

class Coin coin1: Coin

face = 0

coin2: Coin

face = 1

Page 16: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

16

Example 2: The BankAccount Class

We define an BankAccount class to model a bank account Design questions:

State: what field(s) do we need to represent the state of a bank acct?• acctNumber,an integer • acctName, a string• balance, an integer

Behaviors/operations: what are some common behaviors of a bank account in a simple banking context?

• A constructor, to set up the object

• a getBalance method, to return balance• a toString method, to return a string description of the current state

• a withdraw method, to withdraw from the account• a deposit method, to deposit into the account• a addInterest method, to add interest

See BankAccount.java, Transactions.java

Page 17: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

17

Example 2: Account and Transactionspublic class BankAccount { final double RATE = 0.035; long acctNumber; String acctName; double balance;

public BankAccount (String owner, long account, double initial) {

acctName = owner; acctNumber = account; balance = initial; }

public double deposit (double amount) {

balance = balance + amount;

return balance; } …}

public static void main (String[] args) { BankAccount aliceAcct =

new BankAccount (“Alice", 11111, 100.00);

BankAccount bobAcct = new BankAccount (“Bob", 22222, 200.00);

BankAccount charlesAcct = new BankAccount (“Charles", 33333, 300.00);

bobAcct.deposit (30.00); …}

Page 18: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

18

Example 2: The Three BankAccount Objects in Transactions

aliceAcct: BankAccount

acctNumber = 11111acctName = “Alice”balance = 100.00

bobAcct: BankAccount

acctNumber = 22222acctName = “Bob”balance = 200.00

charlesAcct: BankAccount

acctNumber = 33333acctName = “Charles”balance = 300.00

After bobAcct.deposit (30.00);

aliceAcct: BankAccount

acctNumber = 11111acctName = “Alice”balance = 100.00

bobAcct: BankAccount

acctNumber = 22222acctName = “Bob”balance = 230.00

charlesAcct: BankAccount

acctNumber = 33333acctName = “Charles”balance = 300.00

Page 19: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

19

Example 3: The Ball Class

We define a Ball class to model self-bouncing balls

Page 20: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

20

Example 3: The Ball Class

Design questions: State: what field(s) do we need to represent the state of a self-

bouncing ball?• rx, ry, current position• vx, vy, speed• color, current color• left, right, bottom, top:cage (boundaries)

Behaviors/operations: what are some common behaviors of a self-bouncing ball?

• A default constructor, to set up a random ball in unit square• A constructor, to set up a ball with given parameters

• A move method, to update position• A draw method, to display

See Ball.java, BouncingBalls.java

Page 21: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Example 3: Bouncing Ball in Unit Square

public class Ball {

double rx, ry; double vx, vy; double radius;

public Ball() { rx = ry = 0.5; vx = 0.015 - Math.random() * 0.03; vy = 0.015 - Math.random() * 0.03; radius = 0.01 + Math.random() * 0.01; }

public void move() { if ((rx + vx > 1.0) || (rx + vx < 0.0)) vx = -vx; if ((ry + vy > 1.0) || (ry + vy < 0.0)) vy = -vy; rx = rx + vx; ry = ry + vy; }

public void draw() { StdDraw.filledCircle(rx, ry, radius); }}

instance variables

Ball.java

bounce

constructor

methods

Page 22: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Object References

Allow client to manipulate an object as a single entity. Essentially a machine address (pointer).

Ball b1 = new Ball();b1.move();b1.move();

Ball b2 = new Ball();b2.move();

b2 = b1;b2.move();

main memory(64-bit machine)

100 0

101 0

102 0

103 0

104 0

105 0

106 0

107 0

108 0

109 0

110 0

111 0

112 0

addr value

Page 23: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Object References

Allow client to manipulate an object as a single entity. Essentially a machine address (pointer).

Ball b1 = new Ball();b1.move();b1.move();

Ball b2 = new Ball();b2.move();

b2 = b1;b2.move();

main memory(64-bit machine)

100 0

101 0

102 0

103 0

104 0

105 0

106 0

107 0

108 0

109 0

110 0

111 0

112 0

100

registers

0.50

0.50

0.05

0.01

0.03

addr value

b1

Page 24: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Object References

Allow client to manipulate an object as a single entity. Essentially a machine address (pointer). 0.50

0.50

0.05

0.01Ball b1 = new Ball();b1.move();b1.move();

Ball b2 = new Ball();b2.move();

b2 = b1;b2.move();

main memory(64-bit machine)

100

101

102

103

104 0.03

105 0

106 0

107 0

108 0

109 0

110 0

111 0

112 0

100

registers

0.55

0.51

addr value

b1

Page 25: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Object References

Allow client to manipulate an object as a single entity. Essentially a machine address (pointer).

Ball b1 = new Ball();b1.move();b1.move();

Ball b2 = new Ball();b2.move();

b2 = b1;b2.move();

main memory(64-bit machine)

100 0.55

101 0.51

102 0.05

103 0.01

104 0.03

105 0

106 0

107 0

108 0

109 0

110 0

111 0

112 0

100

registers

0.60

0.52

addr value

b1

Page 26: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Object References

Allow client to manipulate an object as a single entity. Essentially a machine address (pointer).

Ball b1 = new Ball();b1.move();b1.move();

Ball b2 = new Ball();b2.move();

b2 = b1;b2.move();

main memory(64-bit machine)

100 0.60

101 0.52

102 0.05

103 0.01

104 0.03

105 0

106 0

107 0

108 0

109 0

110 0

111 0

112 0

100

registers

107 0.50

0.50

0.07

0.04

0.04

addr value

b1

b2

Page 27: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Object References

Allow client to manipulate an object as a single entity. Essentially a machine address (pointer).

Ball b1 = new Ball();b1.move();b1.move();

Ball b2 = new Ball();b2.move();

b2 = b1;b2.move();

main memory(64-bit machine)

100 0.60

101 0.52

102 0.05

103 0.01

104 0.03

105 0

106 0

107 0.50

108 0.50

109 0.07

110 0.04

111 0.04

112 0

107

registers

100

0.57

0.54

addr value

b1

b2

Page 28: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Object References

Allow client to manipulate an object as a single entity. Essentially a machine address (pointer).

Ball b1 = new Ball();b1.move();b1.move();

Ball b2 = new Ball();b2.move();

b2 = b1;b2.move();

main memory(64-bit machine)

100 0.60

101 0.52

102 0.05

103 0.01

104 0.03

105 0

106 0

107 0.57

108 0.54

109 0.07

110 0.04

111 0.04

112 0

100

registers

100

addr value

b1

b2

Data stored in 107 – 111 for bit recycler (garbage collection).

Page 29: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Object References

Allow client to manipulate an object as a single entity. Essentially a machine address (pointer).

Ball b1 = new Ball();b1.move();b1.move();

Ball b2 = new Ball();b2.move();

b2 = b1;b2.move();

main memory(64-bit machine)

100

addr

0.60

value

101 0.52

102 0.05

103 0.01

104 0.03

105 0

106 0

107 0.57

108 0.54

109 0.07

110 0.04

111 0.04

112 0

100

b1

Moving b2 also moves b1 since they are aliases that reference the same object.

registers

100

b2

0.65

0.53

Page 30: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Creating Many Objects Each object is a data type value.

Use new to invoke constructor and create each one.

public class BouncingBalls { public static void main(String[] args) {

int N = Integer.parseInt(args[0]); Ball balls[] = new Ball[N]; for (int i = 0; i < N; i++) balls[i] = new Ball();

while(true) { StdDraw.clear(); for (int i = 0; i < N; i++) { balls[i].move(); balls[i].draw(); } StdDraw.show(20); } }}

create and initializeN objects

animation loop

Page 31: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

31

Example 4: Continuous Line Graph What is a base class to allow drawing of

continuous line graphs?

http://en.wikipedia.org/wiki/Turtle_graphics

Page 32: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

32

Example: Turtle

We define a Tutle class to keep track of drawing turtle (cursor)

Design questions: State: what field(s) do we need to represent the

state of a drawing turtle?• x,y, current position• angle: the current drawing direction

Operations: what are some common behaviors/operations on a Turle to allow flexible drawing?

• A Turtle constructor, to set up the object

• A goForward( stepSize) method• a turnLeft( angle ) method

Page 33: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Turtle Graphicspublic class Turtle { double x, y; // turtle is at (x, y) double angle; // facing this direction public Turtle(double x0, double y0, double a0) { x = x0; y = y0; angle = a0; }

public void turnLeft(double delta) { angle += delta; }

public void goForward(double d) { double oldx = x; double oldy = y; x += d * Math.cos(Math.toRadians(angle)); y += d * Math.sin(Math.toRadians(angle)); StdDraw.line(oldx, oldy, x, y); } …}

33

Page 34: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

N-gon

3 7 1440

34

What is the angle of each turn? angle = 360/ N

What is the initial degree? angle / 2

Page 35: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

N-gon

3 7 1440

public class Ngon { public static void main(String[] args) { int N = Integer.parseInt(args[0]); double angle = 360.0 / N; Turtle turtle = new Turtle(0.5, 0, angle/2.0);

double step = Math.sin(Math.toRadians(angle/2.0)); for (int i = 0; i < N; i++) { turtle.goForward(step); turtle.turnLeft(angle); } }}

35

Page 36: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Spira Mirabilis

public class Spiral { public static void main(String[] args) { int N = Integer.parseInt(args[0]); double decay = Double.parseDouble(args[1]); double angle = 360.0 / N; double step = Math.sin(Math.toRadians(angle/2.0)); Turtle turtle = new Turtle(0.5, 0, angle/2.0); for (int i = 0; i < 10 * N; i++) { step /= decay; turtle.goForward(step); turtle.turnLeft(angle); } }}

36

Page 37: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

37

Spira Mirabilis

3 1.0 3 1.2 1440 1.00004 1440 1.0004

public class Spiral { public static void main(String[] args) { int N = Integer.parseInt(args[0]); double decay = Double.parseDouble(args[1]); double angle = 360.0 / N; double step = Math.sin(Math.toRadians(angle/2.0)); Turtle turtle = new Turtle(0.5, 0, angle/2.0); for (int i = 0; i < 10 * N; i++) { step /= decay; turtle.goForward(step); turtle.turnLeft(angle); } }}

37

Page 38: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Spira Mirabilis in Nature

38

Page 39: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Caution

René Magritte. "This is not a pipe."

Java. This is not a Turtle.

OOP. Natural vehicle for studying abstract models of the real world.

Turle myTurtle = new Turtle(0.5, 0, 45);myTurle.turnLeft( 90 );

Page 40: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

40

Example 5: A Complex Class A complex number (a + bi) is a quintessential

mathematical abstraction (a + bi) + (c + di) = a + c + (b + d)i (a + bi) x (c + di) = ac - bd + (ad + bc)i

Many applications of complex numbers Fractals. Impedance in RLC circuits. Signal processing and Fourier analysis. Control theory and Laplace transforms. Quantum mechanics and Hilbert spaces.

a = 3 + 4i, b = -2 + 3i

a + b = 1 + 7i

a b = -18 + i

| a | = 5

Page 41: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Argos

41

Antennas

Page 42: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

42

A Complex Class

Design questions: State: what field(s) do we need to represent the state of a

complex number?• re, a number representing the real part• im, a number representing the imaginary part

Behaviors: what are some common behaviors of a complex number?

• a Complex constructor, to set up the object

• A abs method, to return the 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– …

Page 43: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

43

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

… }

- What is the return type of plus?- Should plus change the state of the

number

Page 44: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

44

The Consistency (Familiarity) Design Principle

Suppose a, b, and c are standard numbers (Complex numbers are numbers after all)Does a + b (think a.+(b) ) change a?

• noWhat is the return of a + b (think a.+

(b)?• The value of a + b so that we can write a + b + c

State (no)change and return type of plus double real = re + b.re;

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

Page 45: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

45

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 46: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

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 47: CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

47

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 = 3.0 + 4.0ib = -2.0 + 3.0ic = -18.0 + 1.0i