Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

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

2 2 Admin  PS6 (Sukoku) questions  Friday’s class

3 Recap: Design and Implementation Methodology: Procedural Based  Design (goal oriented) m top-down stepwise goal-driven method decomposition m methods designed are those needed for the current goal m verb driven  Program implementation and testing m bottom-up 3

4 Recap: Design and Implementation Methodology: Object-Oriented  Design m Identify objects that are part of the problem domain or solution Each object has state (variables) Each object has behaviors (methods) m Often do not consider one specific goal, but rather a context m noun driven 4

5 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

6 Recap: Class Definition Components r Variables m fields (instance variables per object) m static variables (shared by all objects) r Methods m static methods (method usable with or without object) Can access only static variables m 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

7 Point class: Variables public class Point { // fields (instance variables, attributes) int x; int y; // static variables shared by all objects static int numPoints = 0;

8 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); }

9 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; }

10 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() ); }

11 Point class as blueprint m The class (blueprint) will describe how to create objects. m Each object will contain its own data and methods. Point class state: int x, y behavior: 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() …

12 12 Outline  Admin and recap  Defining classes o Motivation and basic syntax  Examples

13 Design and Implementation Methodology: Object-Oriented r Design m Identify objects (nouns) and their behaviors m Often do not consider one specific goal, but rather a context m Often lead to more reusable, extensible software 13

14 14 Example 1: A Coin Class  We define a Coin class to model a coin in heads-tails games r 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 m 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

15 15 Instance Data: The Two Coins in FlipRace int face; class Coin coin1: Coin face = 0 coin2: Coin face = 1

16 16 Example 2: The BankAccount Class  We define an BankAccount class to model a bank account r 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 m 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

17 17 Example 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); … }

18 18 Example 2: The Three BankAccount Objects in Transactions aliceAcct: BankAccount acctNumber = 11111 acctName = “Alice” balance = 100.00 bobAcct: BankAccount acctNumber = 22222 acctName = “Bob” balance = 200.00 charlesAcct: BankAccount acctNumber = 33333 acctName = “Charles” balance = 300.00 After bobAcct.deposit (30.00); aliceAcct: BankAccount acctNumber = 11111 acctName = “Alice” balance = 100.00 bobAcct: BankAccount acctNumber = 22222 acctName = “Bob” balance = 230.00 charlesAcct: BankAccount acctNumber = 33333 acctName = “Charles” balance = 300.00

19 19 Example 3: The Ball Class  We define a Ball class to model self-bouncing balls

20 20 Example 3: The Ball Class r 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) m 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

21 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

22 Object References  Allow client to manipulate an object as a single entity.  Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) 1000 1010 1020 1030 1040 1050 1060 1070 1080 1090 1100 1110 1120 addrvalue

23 Object References  Allow client to manipulate an object as a single entity.  Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) 1000 1010 1020 1030 1040 1050 1060 1070 1080 1090 1100 1110 1120 100 registers 0.50 0.05 0.01 0.03 addrvalue b1

24 Object References  Allow client to manipulate an object as a single entity.  Essentially a machine address (pointer). 0.50 0.05 0.01 Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) 100 101 102 103 1040.03 1050 1060 1070 1080 1090 1100 1110 1120 100 registers 0.55 0.51 addrvalue b1

25 Object References  Allow client to manipulate an object as a single entity.  Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) 1000.55 1010.51 1020.05 1030.01 1040.03 1050 1060 1070 1080 1090 1100 1110 1120 100 registers 0.60 0.52 addrvalue b1

26 Object References  Allow client to manipulate an object as a single entity.  Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) 1000.60 1010.52 1020.05 1030.01 1040.03 1050 1060 1070 1080 1090 1100 1110 1120 100 registers 107 0.50 0.07 0.04 addrvalue b1 b2

27 Object References  Allow client to manipulate an object as a single entity.  Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) 1000.60 1010.52 1020.05 1030.01 1040.03 1050 1060 1070.50 1080.50 1090.07 1100.04 1110.04 1120 107 registers 100 0.57 0.54 addrvalue b1 b2

28 Object References  Allow client to manipulate an object as a single entity.  Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) 1000.60 1010.52 1020.05 1030.01 1040.03 1050 1060 1070.57 1080.54 1090.07 1100.04 1110.04 1120 100 registers 100 addrvalue b1 b2 Data stored in 107 – 111 for bit recycler (garbage collection).

29 Object References  Allow client to manipulate an object as a single entity.  Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) 100 addr 0.60 value 1010.52 1020.05 1030.01 1040.03 1050 1060 1070.57 1080.54 1090.07 1100.04 1110.04 1120 100 b1 Moving b2 also moves b1 since they are aliases that reference the same object. registers 100 b2 0.65 0.53

30 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 initialize N objects animation loop

31 31 Example 4: Continuous Line Graph r What is a base class to allow drawing of continuous line graphs? http://en.wikipedia.org/wiki/Turtle_graphics

32 32 Example: Turtle  We define a Tutle class to keep track of drawing turtle (cursor) r 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 m 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

33 Turtle 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); } … } 33

34 N-gon 3 7 1440 34 What is the angle of each turn? angle = 360/ N What is the initial degree? angle / 2

35 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

36 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

37 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

38 Spira Mirabilis in Nature 38

39 Caution r René Magritte. "This is not a pipe." r Java. This is not a Turtle. r OOP. Natural vehicle for studying abstract models of the real world. Turle myTurtle = new Turtle(0.5, 0, 45); myTurle.turnLeft( 90 );

40 40 Example 5: A Complex Class 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 Many applications of complex numbers m Fractals. m Impedance in RLC circuits. m Signal processing and Fourier analysis. m Control theory and Laplace transforms. m Quantum mechanics and Hilbert spaces. a = 3 + 4i, b = -2 + 3i a + b = 1 + 7i a  b = -18 + i | a | = 5

41 Argos 41 Antennas

42 42 A Complex Class r 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 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 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 –…–…

43 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

44 44 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); }

45 45 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

46 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.

47 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.0i b = -2.0 + 3.0i c = -18.0 + 1.0i


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

Similar presentations


Ads by Google