520 likes | 533 Views
Learn about memory management in Java, including the stack and heap, value of reference variables, and "has-a" relationships between objects. Also, explore examples of moving points and circles.
E N D
Interacting ClassesLecture #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
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!
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.
Midterm You are turning into real programmers now. In future quizzes and exams there will be more questions like this:
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
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.
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
“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:
DormRoom: Code and UML 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; } }
Freshman Code and UML 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;} }
Computer Scientist of the Week Fred Brooks 1931- • 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.
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.
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; } }
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; } }
Complex objects Point p = new Point(1, 2); Circle c = new Circle(p, .5); c.getCenter().getX() 1 ??
public class Circle { private Point center; private double radius; … public void move(double dx, double dy) { center.move(dx, dy); } } Moving a Circle • To move a circle move its center
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
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) …
Aliases 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 • Several variables can refer to the same object—aliasing
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() ?
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
Explorer knowledge • Name: name • Location in maze (room): location • How much annoyance it can inflict: strength • How much annoyance it can tolerate: tolerance
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
Create and query an explorer public class Explorer { private String name; private Roomlocation; 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 Roomlocation() { return location; } public int strength() { return strength; } public int tolerance() { return tolerance; } ... }
Command an explorer - fill in ??? public class Explorer { private String name; private Roomlocation; private int strength; private int tolerance; ... public void move(RoomnewRoom) { ????????????? } public void takeThat(int hitStrength) { ????????????? } public void poke(Denizen opponent) { opponent.takeThat(strength); } }
Command an explorer public class Explorer { private String name; private Roomlocation; private int strength; private int tolerance; ... public void move(RoomnewRoom) { location = newRoom; } public void takeThat(int hitStrength) { tolerance -= hitStrength; } public void poke(Denizen opponent) { opponent.takeThat(strength); } }
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
Interactive system Interface Controller Input Model input in Java is more complicated and will be discussed later View Output
Reminder: points and circles • Point constructor public Point(double x, double y) • Point queries public double getX() public double getY() • Circle constructor public Circle(Pointcenter, double radius) • Circle queries public PointgetCenter() public double getRadius()
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
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
Point viewer public class PointViewer { private Pointpoint; public PointViewer(Pointp) { point = p; } public void display() { System.out.println("A point at " + point.getX() + ", " + point.getY()); } }
Circle viewer public class CircleViewer { private Circlecircle; public CircleViewer(Circlec) { circle = c; } public void display() { System.out.println("A circle at " + circle.getCenter().getX() + ", " + circle.getCenter().getY() + "with radius" + circle.getRadius()); } }
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
The main program public class PointCircleDisplay { public static void main(String[] args) { Pointp = new Point(2, 3); PointViewerpv = new PointViewer(p); pv.display(); p.move(1, -1); pv.display(); Circlec = new Circle(p, 1); CircleViewercv = new CircleViewer(c); cv.display(); p.move(.5,-2); cv.display(); } }
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
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
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
Issuing tickets • The static variable issued tracks the total number of Ticket objects • The instance (dynamic) variable number stores the number of a particular Ticket object Tickett1 = new Ticket(); t1.getNumber() 0 Tickett2 = new Ticket(); t2.getNumber() 1 Ticket.getIssued() 2