Presentation is loading. Please wait.

Presentation is loading. Please wait.

Interacting Classes Lecture #6 CMPSCI 121, Spring 2005 Introduction to Problem Solving with Computers Prof. McCallum No quiz today. It will again be in.

Similar presentations


Presentation on theme: "Interacting Classes Lecture #6 CMPSCI 121, Spring 2005 Introduction to Problem Solving with Computers Prof. McCallum No quiz today. It will again be in."— Presentation transcript:

1 Interacting Classes Lecture #6 CMPSCI 121, Spring 2005 Introduction to Problem Solving with Computers Prof. McCallum No quiz today. It will again be in lab on Thursday. (Read Chapter 3). OWL Written Exercise is due Thursday 9am. Programming Assignment #5 was due this morning. Today’s music: Aaron Copland, 1846. Hungarian Rhapsody #2

2 1 Midterm Results Finished grading same day you took it; back to you in labs. On the whole you did very well! Congratulations! You have learned a lot! Average: 80 (+11 EC), Median: 81, Min: 27, Max: 100 (x5) Midterm roughly: A 100-90 (#46) B 89-80 (#54) B- 79-75 (#23) C 74-65 (#22) D 64-50 (#15) F 49-0 (#11) Subject to change!

3 2 Dropping? I hope not, and that you’ll stick with it! But if you can’t: Last day (without the need to petition the Dean) is Monday the 30th Can go to Pauline at the front desk in the CS main office.

4 3 Midterm You are turning into real programmers now. In future quizzes and exams there will be more questions like this:

5 4 Pace of the course Steep and fast in beginning Slowed down before midterm It’s been 3 weeks since we’ve had a new concept in this course! Now after the midterm, steep and fast again Next three weeks are crucial Work hard. Don’t fall behind. Read the text book!

6 5 Primitive and Reference Types We’ve seen Java’s 8 primitive types: int, double, boolean, char (also byte, short, long, float) Java also has reference types, for objects Examples of reference variables: String name; Counter c1; They are called references because they refer to a memory location where the object lives

7 6 Memory: Stack and Heap When we use the DrJava interactions pane, and when we run a standalone Java program or applet, memory is allocated for variables and objects Understanding how this memory is managed helps us understand how Java works The JVM uses a stack and a heap. The stack is used to store: Variables we create in the DrJava interactions pane A “stack frame” for each active method call (we’ll discuss this later in the course) The heap is used to store objects.

8 7 How the Stack Grows DrJava InteractionsStack > int x; > x = 5; > double min = 0.5; > boolean done = false;

9 8 How the Heap Grows DrJava InteractionsStack and Heap > int x = 99; > Counter c1; > c1 null > c1 = new Counter(); > c1 Counter@2f996f > c1.incrementCount(); > Counter c2 = new Counter(); > c2 Counter@4a0ac5

10 9 Value of a Reference Variable The value of are reference variable is either null or a “heap address” Example: > Counter c1; > c1 null > c1 = new Counter(); > c1 Counter@e05ad6 e05ad6 is a hexadecimal (base 16) number We don’t have to (and can’t) deal with these hex numbers directly

11 10 “Has a” Relationship Example: An object of type A has an instance variable which is an object whose type is B. (A “has a” B.) We will create a DormRoom object, and a Freshman object whose room is that DormRoom UML diagrams that show instance variables and methods:

12 11 DormRoom: Code and UML > DormRoom room = new DormRoom(208, "Hill"); > room.getLocation() "208 Hill" public class DormRoom{ private int num; private String bldgName; public DormRoom(int n, String b){ num = n; bldgName = b; } public String getLocation(){ return num + " " + bldgName; } }

13 12 A DormRoom on the Heap > DormRoom room = new DormRoom(208, "Hill"); > room.getLocation() "208 Hill"

14 13 Freshman Code and UML > DormRoom room = new DormRoom(208, "Hill"); > Freshman f = new Freshman("jo", room); > f.getName() "jo" > f.getRoom().getLocation() "208 Hill" public class Freshman{ private String name; private DormRoom room; public Freshman(String n, DormRoom r){ name = n; room = r; } public String getName(){ return name;} public DormRoom getRoom(){ return room;} }

15 14 A Freshman on the Heap :) > DormRoom room = new DormRoom(208, "Hill"); > Freshman f = new Freshman("jo", room); > f.getName() "jo" > f.getRoom().getLocation() "208 Hill"

16 15 Fred Brooks 1931- Computer Scientist of the Week Ph.D. Harvard, “Applied Math”, 1596 Managed development of OS/390 at IBM. Mythical Man-month “Assigning more programmers to a project running behind schedule, could actually make it even more late” No Silver Bullet “No more technologies or practices that will create a 10-fold improvement in software engineering productivity over 10 years” Winner of Turing Award in 1999.

17 16 Another example... A point on the plane is given by its coordinates x, y in a fixed frame of reference public class Point { private double x, y; Point(double anX, double aY) { x = anX; y = aY; } public double getX() { return x; } public double getY() { return y; } } Add a move(double dx, double dy) method to this class.

18 17 Moving a point Add a moving behavior to Point … with a command public class Point { private double x; private double y; … public void move(double dx, double dy) { x = x + dx; y = y + dy; }

19 18 Moving points

20 19 Building on Point A circle is defined by its center (a point) and its radius (a double) public class Circle { private Point center; private double radius; public Circle(Point aCenter, double aRadius) { center = aCenter; radius = aRadius; } public Point getCenter() { return center; } public double getRadius() { return radius; } }

21 20 Complex objects Point p = new Point(1, 2); Circle c = new Circle(p,.5); c.getCenter().getX()  1 ??

22 21 Moving a Circle public class Circle { private Point center; private double radius; … public void move(double dx, double dy) { center.move(dx, dy); } To move a circle move its center

23 22 Behind the scenes Objects are implemented as chunks of memory Object variables contain the addresses of the chunks, not the chunks themselves That is, object variables hold references to objects

24 23 The reference to nowhere Uninitialized object type variables contain null It's a value in all object types But it refers to no object Often used to indicate missing or optional data Point p = null; Circle c = new Circle(p,.5); c.move(1,1); java.lang.NullPointerException: at Circle.move(Circle.java:33) …

25 24 Resolving method names The name is resolved by the class of the object Point p = new Point(1,1); Circle c = new Circle(1,1,.5); p.move(.5,1).getX()  1.5 c.move(.5,1).getCenter().getX()  1.5

26 25 Aliases Several variables can refer to the same object—aliasing Point p = new Point(1,1); Point p1 = p; p.move(.5, 1); p.getX()  1.5 p1.move(2, 0); p1.getY()  3.5

27 26 The dangers of aliasing… Point p = new Point(1,1); Circle small = new Circle(p,.5); Circle big = new Circle(p, 5); small.move(.5, 2); big.move(5, 20); small.getCenter().getX()  ? big.getCenter().getX()  ?

28 27 … illustrated

29 28 Designing with objects Complex problems involve multiple kinds of objects Stock market: stocks, orders, order books, trades,... Object responsibilities: Knowing facts: stock ticker symbol, order type (buy, sell,...), trade amount,... Doing actions: executing trade, clearing order, updating ask/bid price,...

30 29 Another example: A maze game Maze explorers (just one, representing the player, for now) move around interact with denizens Maze denizens interact with explorers Rooms Where explorers and denizens are located

31 30 Explorer knowledge Name: name Location in maze (room): location How much annoyance it can inflict: strength How much annoyance it can tolerate: tolerance

32 31 Responsibilities and commands Explorer can be told to... Move around: move (to a new location) Fight a denizen: poke (a denizen) Receive a poke from a denizen, decreasing tolerance: takeThat Denizen can be told to... Fight an explorer: poke (an explorer) Receive a poke from an explorer: takeThat

33 32 Interaction diagram

34 33 An explorer gets hit

35 34

36 35 Create and query an explorer public class Explorer { private String name; private Room location; private int strength; private int tolerance; public Explorer(String nm, Room loc, int str, int tol) { name = nm; location = loc; strength = str; tolerance = tol; } public String name() { return name; } public Room location() { return location; } public int strength() { return strength; } public int tolerance() { return tolerance; }... }

37 36 Command an explorer - fill in ??? public class Explorer { private String name; private Room location; private int strength; private int tolerance;... public void move(Room newRoom) { ????????????? } public void takeThat(int hitStrength) { ????????????? } public void poke(Denizen opponent) { opponent.takeThat(strength); }

38 37 Command an explorer public class Explorer { private String name; private Room location; private int strength; private int tolerance;... public void move(Room newRoom) { location = newRoom; } public void takeThat(int hitStrength) { tolerance -= hitStrength; } public void poke(Denizen opponent) { opponent.takeThat(strength); }

39 38 MazeWorld in action

40 39 A Movie with a Sequel

41 40 A complete system Model: represents the objects and relationships of interest characters, rooms,... in video game your bank account(s) Interface: allows a user (or another system) to interact with the model graphics, joystick commands ATM

42 41 Interactive system Controller Model View Interface Input Output input in Java is more complicated and will be discussed later

43 42 Reminder: points and circles Point constructor public Point(double x, double y) Point queries public double getX() public double getY() Circle constructor public Circle(Point center, double radius) Circle queries public Point getCenter() public double getRadius()

44 43 Setting up a view Define viewers for different classes of objects Point viewer PointViewer Constructor: public PointViewer(Point p) Viewing command: public void display() Circle viewer CircleViewer Constructor: public CircleViewer(Circle c) Viewing command: public void display() A viewer keeps a reference to its object If the object changes, the next display call shows the changed object

45 44 Displaying In a more “real” system, displaying might involve graphics, for example Here we use the simplest form of output The built-in System.out object provides a channel to the standard output device (the screen) Output command public void println(String s) Write a line with text s on the standard output device

46 45 Point viewer public class PointViewer { private Point point; public PointViewer(Point p) { point = p; } public void display() { System.out.println("A point at " + point.getX() + ", " + point.getY()); }

47 46 Circle viewer public class CircleViewer { private Circle circle; public CircleViewer(Circle c) { circle = c; } public void display() { System.out.println("A circle at " + circle.getCenter().getX() + ", " + circle.getCenter().getY() + " with radius " + circle.getRadius()); }

48 47 Getting it started We’ve been using DrJava to create objects and interact with them What if we want our Java code to work on its own? We need a stand-alone way of creating the appropriate objects and and making them work for us The main method: the Java virtual machine calls it to start the execution of a Java program

49 48 The main program public class PointCircleDisplay { public static void main(String[] args) { Point p = new Point(2, 3); PointViewer pv = new PointViewer(p); pv.display(); p.move(1, -1); pv.display(); Circle c = new Circle(p, 1); CircleViewer cv = new CircleViewer(c); cv.display(); p.move(.5,-2); cv.display(); }

50

51 50 Two roles for classes So far: classes as templates for objects instance variables: object data methods: object functionality But also: classes as containers for functionality and data that does not need multiple instances

52 51 What goes into a class Static: same independently of how they are accessed Variables: same value Methods: same computation Dynamic: different for different class instances Variables: different values Methods: computation may depend on instance variables

53 52 Putting it all together Using static and dynamic: numbered tickets public class Ticket { private static int issued; public static int getIssued(){ return issued; } private int number; public Ticket() { number = issued++; } public int getNumber() { return number; } static dynamic

54 53 Issuing tickets Ticket t1 = new Ticket(); t1.getNumber()  0 Ticket t2 = new Ticket(); t2.getNumber()  1 Ticket.getIssued()  2 The static variable issued tracks the total number of Ticket objects The instance (dynamic) variable number stores the number of a particular Ticket object

55 54 Classes as containers Container for a set of related static methods and variables To access non-private static members of class X variable: X.var method: X.meth(...)

56 55 Example: the Math class Defines common mathematical constants and functions Math.PI  3.141592653589793 Math.sin(Math.PI/2)  1.0 Math.log(Math.E)  1.0 Math.pow(2,3)  8.0 Math.pow(2, 0.5)  1.4142135623730951 Math.sqrt(3*3 + 4*4)  5.0

57 56 Method Overloading There are in fact two max methods The appropriate one is chosen from the argument types Math.max(1, 2)  2 Math.max(1.0, 2.0)  2.0 static int max(int a, int b) static double max(double a, double b)

58 57 Named constants Name light values to isolate clients from specific values public class TrafficSignal { public static final int GREEN = 0; public static final int YELLOW = 1; public static final int RED = 2;... } shared by all instancescannot change value TrafficSignal.YELLOW  1

59 58 Summary: how to refer to what staticdynamic what from variable sv method sm variable dv method dm anywhere C.sv o.sv C.sm() o.sm() o.dvo.dm() static methods of C svsm() —— dynamic methods of C svsm()dvdm() Class C, o instance of C

60 59 Final Why can't we (as an Indiana legislator tried to pass into law in 1897)? “Variables” intended to hold fixed values (constants) should be declared final Final variables can be assigned to just once Math.PI = 3.0;

61 60 Final variables can be dynamic public class Ticket { private static int issued; public static int getIssued(){ return issued; } private final int number; public Ticket() { number = issued++; } public int getNumber() { return number; } ensure ticket number can't change

62 61 The traffic signal again public class TrafficSignal { public static final int GREEN = 0; public static final int YELLOW = 1; public static final int RED = 2; public static int nextLight(int color) { return (color + 1) % 3; } private int light; public TrafficSignal (int initial) { light = initial; }... } static method

63 62 Operating the signal public class TrafficSignal {... private int light; public int light() { return light; } public void change() { light = nextLight(light); } } static method invocation


Download ppt "Interacting Classes Lecture #6 CMPSCI 121, Spring 2005 Introduction to Problem Solving with Computers Prof. McCallum No quiz today. It will again be in."

Similar presentations


Ads by Google