Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 112 Introduction to Programming User-Defined Data Types: OOP Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone: 432-6400.

Similar presentations


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

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

2 2 Admin  PS6 questions?  PS7 to be officially released tomorrow m Walk through?  Puzzle Day!! m Congratulations to the winning teams! m We will get in touch with each winning team in the next few days on how to give prizes.  Final project m Please start to work on teaming as soon as you can m If you need to find a partner, please send cs112ta@cs.yale.edu a note so that we can arrange meetings at office hours

3 Recap: Digital Audio  Digital audio is samples of audio waves  StdAudio plays/saves audio samples 3

4 Recap: Motivation of Complex (Struct) Data Type Scanner input = new Scanner(new File("cities.txt")); int cityCount = input.nextInt(); int[] xCoords = new int[cityCount]; int[] yCoords = new int[cityCount]; for (int i = 0; i < cityCount; i++) { xCoords[i] = input.nextInt(); yCoords[i] = input.nextInt(); if (distance(xCoords[i], yCoords[i], xCenter, yCenter ) < THRESHOLD) { // draw red } 2 parallel arrays 2 parallel data items Scanner input = new Scanner(new File("cities.txt")); int cityCount = input.nextInt(); Point[] points = new Point[cityCount]; for (int i = 0; i < cityCount; i++) { points[i] = readPoint(input); if ( distance(points[i], pointCenter) < THRESHOLD) { // draw red } points point abstraction

5 Recap: User-Defined Type Concepts : Class, Object, Variable, Field PointMain.java (client program) public class PointMain { main(String args) { Point p1 = new Point(); p1.x = 50; p1.y = 27; Point p2 = p1; Point p3 = new Point(); p3.x = 98; p3.y = 53;... } Point.java (class of objects) public class Point { int x; int y; } x 50 y 27 x 98 y 53 fieldsobjectsclassObject variables (references)

6 Historical Note  Before object-oriented programming, traditional languages (e.g., C ) already have a language structure called struct to allow users to define new data types (combine multiple data fields) beyond primitive types r Object-oriented languages go one step further to organize both data and methods together 6

7 Object Oriented Programming Overview r OOP philosophy. Software is a simulation of the real world. m We know (approximately) how the real world works. m Design software to model the real world. r Procedural programming. [verb-oriented] m Tell the computer to do this. m Tell the computer to do that. r Objected oriented programming (OOP). [noun-oriented] m Identify objects that are part of the problem domain or solution. m Identity: objects are distinguished from other objects (references). m State: objects know things (instance variables). m Behavior: objects do things (methods). 7

8 (Caution) Anti Object Oriented Programming 8

9 Alan Kay r Alan Kay. [Xerox PARC 1970s] m Invented Smalltalk programming language. m Conceived Dynabook portable computer. m Ideas led to: laptop, modern GUI, OOP. Alan Kay 2003 Turing Award “ The computer revolution hasn't started yet. ” “ The best way to predict the future is to invent it. ” “ If you don't fail at least 90 per cent of the time, you're not aiming high enough. ” — Alan Kay 9

10 Motivation: Drawing Points  Suppose our client programs want to draw Point objects: // draw each city Point p1 = new Point(); p1.x = 15; p1.y = 37; StdDraw.filledCircle(p1.x, p1.y, 3); StdDraw.textLeft(p1.x, p1.y, "(" + p1.x + ", " + p1.y + ")” );  To draw multiple points, the same code may be repeated. m We can remove this redundancy using a method.

11 Eliminating Redundancy, Design 1  We can eliminate the redundancy with a static method: // Draws the given point using StdDraw public static void draw(Point p) { StdDraw.filledCircle(p.x, p.y, 3); StdDraw.textLeft(p.x, p.y, "(" + p.x + ", " + p.y + ")” ); }  main would call the method as follows: draw(p1); Question: where do we define the method draw(Point p)?

12 Where do we Define draw(p): Attempt 1: in each client e.g., PointMain1

13 Where do we Define draw(p): Attempt 2: in Point as a Static Method public class Point { int x; int y; public static void draw(Point p) { StdDraw.filledCircle(p.x, p.y, 3); StdDraw.textLeft(p.x, p.y, "(" + p.x + ", " + p.y + ")” ); } Point p1 = new Point(); p1.x = 7; p1.y = 2; Point.draw(p1); Point p2 = new Point(); p2.x = 4; p2.y = 3; Point.draw(p2);

14 Consistent Data Access and Method Access 14 Point p = new Point(); p.x = 10; p.y = 5; Point.draw(p); Accessing point p’s x attribute Accessing point p’s draw behavior p.draw();

15 Instance Methods  instance method (or object method): Exists inside each object of a class and gives behavior to each object. public type name ( parameters ) { statements ; }  same syntax as static methods, but without static keyword Example: public void shout() { System.out.println("HELLO THERE!"); }

16 Instance Method example Instance method (or object method) can access all class scope variables public class Point { int x; int y; // Draws this Point object with the given pen. public void draw() { StdDraw.filledCircle(x, y, 3); StdDraw.textLeft(x, y, "(" + x + ", " + y + ")”); } }  The draw method no longer has a Point p parameter. m How will the method know which point’s x/y to draw? p1: Point x = 50 y = 27 p2: Point x = 98 y = 53

17 Invoking Instance Method  Format. (…)  The provides an implicit parameter 17

18 The Implicit Parameter  During the call p1.draw(); the object referred to by p1 is the implicit parameter.  During the call p2.draw(); the object referred to by p2 is the implicit parameter. p1.draw()draw(p1) p2.draw()draw(p2) r In an instance method, when we refer to a field, we are referring to the field of the implicit parameter. m We say that it executes in the context of a particular object.

19 Summary: Defining Related Method and Data in the Same Class: Instance Method public class Point { int x; int y; public static void draw(Point p) { StdDraw.filledCircle(p.x, p.y, 3); StdDraw.textLeft(p.x, p.y, "(" + p.x + ", " + p.y + ")”); } Point p1 = new Point(); p1.x = 7; p1.y = 2; p1.draw(); // Point.draw(p1); Point p2 = new Point(); p2.x = 4; p2.y = 3; p2.draw(); // Point.draw(p2); p1 provides the implicit parameter: The x and y in draw() are those of the object referenced by p1. p2 provides the implicit parameter: The x and y in draw() are those of the object referenced by p2.

20  Each Point object has its own copy of the draw method, which operates on that object's state: Point p1 = new Point(); p1.x = 7; p1.y = 2; Point p2 = new Point(); p2.x = 4; p2.y = 3; p1.draw(); p2.draw(); public void draw() { // this code can see p1's x and y } Point objects w/ method x 7 y 2 x 4 y 3 public void draw() { // this code can see p2's x and y } p2 p1

21 Static Method vs Instance Method 21 public class Point { int x; int y; public static void draw(Point p) { StdDraw.filledCircle(p.x, p.y, 3, 3); StdDraw.textLeft(p.x, p.y, "(" + p.x + ", " + p.y + ")” ); } public class Point { int x; int y; public static void draw(Point p) { StdDraw.filledCircle(p.x, p.y, 3, 3); StdDraw.textLeft(p.x, p.y, "(" + p.x + ", " + p.y + ")”); }

22 Benefit of Instance Method 22 Point p = new Point(); p.x = 10; p.y = 5; p.draw(); Consistent (same) syntax accessing data and behaviors: a class is an abstraction for a collection of objects with common -data fields (attributes) -behaviors/services (i.e., what such objects can do or be done to them)

23 Instance Method questions  Write an instance method toString to generate string (x, y)  Write an instance method translate that changes a Point 's location by a given dx, dy amount.  Write an instance method distanceFrom that returns the distance between the Point and another point Use the formula:

24 Instance Method answers public class Point { int x; int y; public void translate(int dx, int dy) { x = x + dx; y = y + dy; } public double distanceFrom(Point p) { return Math.sqrt( (x-p.x) * (x-p.x) + (y-p.y) * (y-p.y) ); } public String toString() { return "(" + x + ", " + y + ")“; } public void draw() { StdDraw.filledCircle(x, y, 3); StdDraw.textLeft(x, y, toString()); }

25 Initializing objects  Currently it takes 3 lines to create a Point and initialize it: Point p = new Point(); p.x = 3; p.y = 8; // tedious r We'd rather specify the fields' initial values at the start: Point p = new Point(3, 8); // better! m We are able to do this with most types of objects in Java.

26 Constructors r constructor: a special method to initialize the state of new objects. public type ( parameters ) { statements ; }  runs when the client uses the new keyword m no return type should be specified; it implicitly "returns" the new object being created m If a class has no constructor, Java gives it a default constructor with no parameters that sets all fields to zero- equivalent values.

27 Constructor example public class Point { int x; int y; // Constructs a Point at the given x/y location. public Point(int initialX, int initialY) { x = initialX; y = initialY; } public void translate(int dx, int dy) { x = x + dx; y = y + dy; }... }

28 Client code public class PointMain3 { public static void main(String[] args) { // create two Point objects Point p1 = new Point(5, 2); Point p2 = new Point(4, 3); // print each point System.out.println("p1: (" + p1.x + ", " + p1.y + ")"); System.out.println("p2: (" + p2.x + ", " + p2.y + ")"); // move p2 and then print it again p2.translate(2, 4); System.out.println("p2: (" + p2.x + ", " + p2.y + ")"); } OUTPUT: p1: (5, 2) p2: (4, 3) p2: (6, 7)

29 Multiple Constructors r A class can have multiple constructors. m Each one must accept a unique set of parameters (same rule of method overloading).  Exercise: Write a Point constructor with no parameters that initializes the point to (0, 0).

30 Multiple Constructors  A default Point constructor with no parameters that initializes the point to (0, 0). // Constructs a new point at (0, 0). public Point() { x = 0; y = 0; }

31 Common Constructor Issues 1. By accidentally giving the constructor a return type, it is actually not a constructor, but a method named Point public void Point(int initialX, int initialY) { x = initialX; y = initialY; }

32 Common Constructor Issues 2. Declare a local variable with the same name as a field. The field is "shadowed” by the local variable. Rather than storing value into the field, the param is passed to local variable. The field remains 0. public class Point { int x; int y; public Point(int initialX, int initialY) { int x = initialX; int y = initialY; } … }

33 Common Constructor Issues r shadowing: 2 variables with same name in same scope. m Normally illegal, except when one variable is a field public class Point { int x; int y;... public Point(int x, int y) { System.out.println(“x = “ + x);// para x }  In most of the class, x and y refer to the fields.  In Point(int x, int y), x and y refer to the method's parameters.

34 The this keyword  this : Refers to the implicit parameter inside your class. (a variable that stores the object on which a method is called)  Refer to a field: this. field  Call a method: this. method ( parameters );

35 Fixing Shadowing  To refer to the data field x,say this.x  To refer to the parameter x,say x public class Point { int x; int y;... public Point(int x, int y) { this.x = x; this.y = y; } public void setLocation(int x, int y) { this.x = x; this.y = y; }

36 Calling another constructor public class Point { private int x; private int y; public Point() { this(0, 0); // calls (x, y) constructor } public Point(int x, int y) { this.x = x; this.y = y; }... } Avoids redundancy between constructors Only a constructor (not a method) can call another constructor

37 Summary: 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 objects) 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) 37

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

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

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

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

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

43 Side-by-Side Comparison 43 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

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

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

46 Design and Implementation Methodology: Object-Oriented r 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, to lead to more reusable, extensible software m noun driven 46

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

48 48 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 radius : radius 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

49 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

50 An Array of Objects r It is common that we create an array of objects  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


Download ppt "CS 112 Introduction to Programming User-Defined Data Types: OOP Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone: 432-6400."

Similar presentations


Ads by Google