Title: CS 112 Introduction to Programming
1CS 112 Introduction to Programming
- User-Defined Data Types Examples
- Yang (Richard) Yang
- Computer Science Department
- Yale University
- 308A Watson, Phone 432-6400
- Email yry_at_cs.yale.edu
2Admin
- PS6 (Sukoku) questions
- Fridays class
3Recap Design and Implementation Methodology
Procedural Based
- Design (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
4Recap 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
5Side-by-Side Comparison
Object-oriented
Function-oriented
public class DrawRocket public static void
main(String args) for (int size 3 size
lt 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
lt 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() ...
6Recap 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)
7Point class Variables
- public class Point
- // fields (instance variables, attributes)
- int x
- int y
- // static variables shared by all objects
- static int numPoints 0
-
8Point 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)
-
-
9Point 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
-
-
10Point 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() )
11Point class as blueprint
- Point class
- stateint x, y
- behaviortranslate(int dx, int dy)draw()
- The class (blueprint) will describe how to create
objects. - Each object will contain its own data and methods.
Point object 1 statex 5, y
-2 behaviortranslate(int dx, int dy)draw()
Point object 2 statex -245, y
1897 behaviortranslate(int dx, int dy)draw()
Point object 3 statex 18, y
42 behaviortranslate(int dx, int dy)draw()
12Outline
- Admin and recap
- Defining classes
- Motivation and basic syntax
- Examples
13Design 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
14Example 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
15Instance Data The Two Coins in FlipRace
16Example 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
17Example 2 Account and Transactions
- public 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)
-
-
-
18Example 2 The Three BankAccount Objects in
Transactions
After bobAcct.deposit (30.00)
19Example 3 The Ball Class
- We define a Ball class to model self-bouncing
balls
20Example 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, topcage (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
21Example 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 gt 1.0) (rx vx lt
0.0)) vx -vx if ((ry vy gt 1.0) (ry
vy lt 0.0)) vy -vy rx rx vx
ry ry vy public void draw()
StdDraw.filledCircle(rx, ry, radius)
Ball.java
instance variables
constructor
bounce
methods
22Object References
- Allow client to manipulate an object as a single
entity. - Essentially a machine address (pointer).
addr
value
100
0
101
0
102
0
Ball b1 new Ball() b1.move() b1.move() Ball
b2 new Ball() b2.move() b2 b1 b2.move()
103
0
104
0
105
0
106
0
107
0
108
0
109
0
110
0
111
0
112
0
main memory(64-bit machine)
23Object References
addr
value
- Allow client to manipulate an object as a single
entity. - Essentially a machine address (pointer).
100
0
101
0
102
0
Ball b1 new Ball() b1.move() b1.move() Ball
b2 new Ball() b2.move() b2 b1 b2.move()
b1
103
0
100
104
0
105
0
106
0
107
0
108
0
109
0
110
0
111
0
112
0
registers
main memory(64-bit machine)
24Object References
addr
value
- Allow client to manipulate an object as a single
entity. - Essentially a machine address (pointer).
0.50
100
0.50
101
0.05
102
Ball b1 new Ball() b1.move() b1.move() Ball
b2 new Ball() b2.move() b2 b1 b2.move()
b1
0.01
103
100
104
0.03
105
0
106
0
107
0
108
0
109
0
110
0
111
0
112
0
registers
main memory(64-bit machine)
25Object References
addr
value
- Allow client to manipulate an object as a single
entity. - Essentially a machine address (pointer).
100
0.55
101
0.51
102
0.05
Ball b1 new Ball() b1.move() b1.move() Ball
b2 new Ball() b2.move() b2 b1 b2.move()
b1
103
0.01
100
104
0.03
105
0
106
0
107
0
108
0
109
0
110
0
111
0
112
0
registers
main memory(64-bit machine)
26Object References
addr
value
- Allow client to manipulate an object as a single
entity. - Essentially a machine address (pointer).
100
0.60
101
0.52
102
0.05
Ball b1 new Ball() b1.move() b1.move() Ball
b2 new Ball() b2.move() b2 b1 b2.move()
b1
103
0.01
100
104
0.03
105
0
b2
106
0
107
0
107
108
0
109
0
110
0
111
0
112
0
registers
main memory(64-bit machine)
27Object References
addr
value
- Allow client to manipulate an object as a single
entity. - Essentially a machine address (pointer).
100
0.60
101
0.52
102
0.05
Ball b1 new Ball() b1.move() b1.move() Ball
b2 new Ball() b2.move() b2 b1 b2.move()
b1
103
0.01
100
104
0.03
105
0
b2
106
0
107
0.50
107
108
0.50
109
0.07
110
0.04
111
0.04
112
0
registers
main memory(64-bit machine)
28Object References
addr
value
- Allow client to manipulate an object as a single
entity. - Essentially a machine address (pointer).
100
0.60
101
0.52
102
0.05
Ball b1 new Ball() b1.move() b1.move() Ball
b2 new Ball() b2.move() b2 b1 b2.move()
b1
103
0.01
100
104
0.03
105
0
b2
106
0
107
0.57
100
108
0.54
109
0.07
110
0.04
Data stored in 107 111 for bit recycler
(garbage collection).
111
0.04
112
0
registers
main memory(64-bit machine)
29Object References
addr
value
- Allow client to manipulate an object as a single
entity. - Essentially a machine address (pointer).
100
0.60
101
0.52
102
0.05
Ball b1 new Ball() b1.move() b1.move() Ball
b2 new Ball() b2.move() b2 b1 b2.move()
b1
103
0.01
100
104
0.03
105
0
b2
106
0
107
0.57
100
108
0.54
109
0.07
110
0.04
111
0.04
Moving b2 also moves b1 since they are aliases
that reference the same object.
112
0
registers
main memory(64-bit machine)
30Creating 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(args0) Ball balls
new BallN for (int i 0 i lt N i)
ballsi new Ball() while(true)
StdDraw.clear() for (int i
0 i lt N i) ballsi.move()
ballsi.draw()
StdDraw.show(20)
create and initializeN objects
animation loop
31Example 4 Continuous Line Graph
- What is a base class to allow drawing of
continuous line graphs?
http//en.wikipedia.org/wiki/Turtle_graphics
32Example 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
33Turtle Graphics
public 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)
34N-gon
What is the angle of each turn? angle 360/
N What is the initial degree? angle / 2
3
7
1440
34
35N-gon
public class Ngon public static void
main(String args) int N
Integer.parseInt(args0) 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 lt N i)
turtle.goForward(step)
turtle.turnLeft(angle)
3
7
1440
35
36Spira Mirabilis
public class Spiral public static void
main(String args) int N
Integer.parseInt(args0) double decay
Double.parseDouble(args1) 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 lt 10 N i) step
/ decay turtle.goForward(step)
turtle.turnLeft(angle)
36
37Spira Mirabilis
public class Spiral public static void
main(String args) int N
Integer.parseInt(args0) double decay
Double.parseDouble(args1) 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 lt 10 N i) step
/ decay turtle.goForward(step)
turtle.turnLeft(angle)
3 1.0
3 1.2
1440 1.00004
1440 1.0004
37
38Spira Mirabilis in Nature
38
39Caution
- 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 )
40Example 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
41Argos
41
42A 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
43The 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
44The 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?
- no
- What 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
public Complex plus(Complex b) double
real re b.re double imag im b.im
return new Complex(real, imag)
45Complex.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(rere imim) 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)
instance variables
constructor
refers to b's instance variable
creates a Complex object,and returns a reference
to it
methods
46Immutability 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.
47A 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.0i b -2.0
3.0i c -18.0 1.0i