Interacting Classes Lecture #6 CMPSCI 121, Spring 2005 Introduction to Problem Solving with...
-
Upload
claud-singleton -
Category
Documents
-
view
214 -
download
1
Transcript of Interacting Classes Lecture #6 CMPSCI 121, Spring 2005 Introduction to Problem Solving with...
Interacting ClassesLecture #6
CMPSCI 121, Spring 2005Introduction 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
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
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
MidtermYou are turning into real programmers now.In future quizzes and exams there will be more questions like this:
6
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
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
How the Stack Grows
DrJava Interactions Stack
> int x;
> x = 5;
> double min = 0.5;
> boolean done = false;
9
How the Heap GrowsDrJava Interactions Stack 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
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
“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
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
A DormRoom on the Heap
> DormRoom room = new DormRoom(208, "Hill");
> room.getLocation()
"208 Hill"
14
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
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
Fred Brooks1931-
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.
QuickTime™ and aTIFF (Uncompressed) decompressor
are needed to see this picture.
QuickTime™ and aTIFF (Uncompressed) decompressor
are needed to see this picture.
17
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
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
Moving points
20
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
Complex objectsPoint p = new Point(1, 2);Circle c = new Circle(p, .5);
c.getCenter().getX() 1??
22
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
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
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) …
26
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.5p1.move(2, 0); p1.getY() 3.5
27
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
… illustrated
30
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
Explorer knowledge Name: name Location in maze (room): location How much annoyance it can inflict: strength
How much annoyance it can tolerate: tolerance
32
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
Interaction diagram
34
An explorer gets hit
35
36
Create and query an explorerpublic 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
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
Command an explorerpublic 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
MazeWorld in action
40
A Movie with a Sequel
41
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
Interactive system
Controller
Model
View
Interface
Input
Output
input in Java is more complicated and will be discussed later
43
Reminder: points and circles Point constructor
public Point(double x, double y) Point queries
public double getX()public double getY()
Circle constructorpublic Circle(Point center, double radius)
Circle queriespublic Point getCenter()public double getRadius()
44
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
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
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
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
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
The main programpublic 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(); }}
51
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
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
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
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
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
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