470 likes | 484 Views
Learn about user-defined data types in programming with examples, methodologies, and comparisons between Object-Oriented and Function-Oriented design. Explore class components, methods, constructors, and more. Includes examples of Point class and Coin class.
E N D
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
Admin • PS6 (Sukoku) questions • Friday’s class
Recap: 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
Recap: Design and Implementation Methodology: Object-Oriented • Design • Identify objectsthat 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
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 draw(){ printCap(); ... } ... public void printCap(){ ... } }
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)
Point class: Variables public class Point { // fields (instance variables, attributes) int x; int y; // static variables shared by all objects static int numPoints = 0;
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); }
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; }
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() ); } }
Point class as blueprint Point class state:int x, y behavior:translate(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 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()…
Outline • Admin and recap • Defining classes • Motivation and basic syntax • Examples
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
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 isHeadsmethod, 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
class Coin coin1: Coin coin2: Coin intface; face = 0 face = 1 Instance Data: The Two Coins in FlipRace
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
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); … } Example 2: Account and Transactions
aliceAcct: BankAccount bobAcct: BankAccount charlesAcct: BankAccount aliceAcct: BankAccount bobAcct: BankAccount charlesAcct: BankAccount acctNumber = 11111 acctName = “Alice” balance = 100.00 acctNumber = 22222 acctName = “Bob” balance = 200.00 acctNumber = 33333 acctName = “Charles” balance = 300.00 acctNumber = 11111 acctName = “Alice” balance = 100.00 acctNumber = 22222 acctName = “Bob” balance = 230.00 acctNumber = 33333 acctName = “Charles” balance = 300.00 Example 2: The Three BankAccount Objects in Transactions After bobAcct.deposit (30.00);
Example 3: The Ball Class • We define a Ball class to model self-bouncing balls
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 movemethod, to update position • A drawmethod, to display See Ball.java, BouncingBalls.java
Example 3: Bouncing Ball in Unit Square publicclass 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); } } Ball.java instance variables constructor bounce methods
Object 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)
0.50 0.50 0.05 0.01 0.03 Object 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)
0.55 0.51 Object References addr value • Allow client to manipulate an object as a single entity. • Essentially a machine address (pointer). 100 0.50 101 0.50 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)
0.60 0.52 Object 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)
0.50 0.50 0.07 0.04 0.04 Object 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 107 0 108 0 109 0 110 0 111 0 112 0 registers main memory(64-bit machine)
0.57 0.54 Object 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 107 0.50 108 0.50 109 0.07 110 0.04 111 0.04 112 0 registers main memory(64-bit machine)
Object 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 100 107 0.57 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)
0.65 0.53 Object 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 100 107 0.57 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)
Creating Many Objects • Each object is a data type value. • Use new to invoke constructor and create each one. publicclass BouncingBalls { publicstaticvoid 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
Example 4: Continuous Line Graph • What is a base class to allow drawing of continuous line graphs? http://en.wikipedia.org/wiki/Turtle_graphics
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
Turtle Graphics publicclass 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; } publicvoid turnLeft(double delta) { angle += delta; } publicvoid 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); } … }
N-gon What is the angle of each turn? angle = 360/ N What is the initial degree? angle / 2 3 1440 7 34
N-gon publicclass Ngon { publicstaticvoid 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); } } } 3 1440 7 35
Spira Mirabilis publicclass Spiral { publicstaticvoid 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
Spira Mirabilis publicclass Spiral { publicstaticvoid 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); } } } 1440 1.00004 3 1.2 3 1.0 1440 1.0004 37
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. TurlemyTurtle=new Turtle(0.5,0, 45); myTurle.turnLeft( 90 );
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 ab = -18 + i | a | = 5
Argos Antennas 41
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 • …
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
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? • 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; returnnew Complex(real,imag); }
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
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.
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 = 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