CS151 lecture notes, Fall 1999 Week 8, Friday Hand back exams. Review quiz10 Start reading Chapter 9 Quiz Monday on Chapter 8 Passing objects as parameters ----------------------------- public static void printPoint (Point p) { System.out.println ("(" + p.x + ", " + p.y + ")"); } This method take a single Point as an argument, and prints the instance variables in a nice format. You would invoke it like this: Point blank = new Point (3, 4); printPoint (blank); As usual, the name of the argument has nothing to do with the name of the parameter. Draw a stack diagram of this method being invoked. blank (in main) and p (in printPoint) are different Point variables that refer to the same Point object. That's ok. In fact, that's what makes it possible for the two methods to share information. (Someone last time asked if objects are a way to make information globally accessible. The answer is sort of -- they allow you to share containers between methods). The usual rules of composition apply: printPoint (new Point (3, 4)); The thing in parentheses is an expression with type Point, and is therefor a legal argument for the printPoint method. A second kind of object ----------------------- Java also has a built-in Rectangle object. A Rectangle object has nothing to do with the rectangles we draw on the screen. You cannot draw a Rectangle object and you cannot see it. A rectangle object is four integers. Nothing more, nothing less. The names of the instance variables are x, y, width, and height. You can create a Rectangle without initializing the instance variables: Rectangle box = new Rectangle (); And then you can fill in the instance variables: box.x = box.y = ... Or you can do both at the same time: Rectangle box = new Rectangle (0, 0, 100, 200); In both cases the picture is the same. We extract the instance variables of this Rectangle using dot notation. Returning objects from methods ------------------------------ public static Point findCenter (Rectangle box) { int x = box.x + box.width/2; int y = box.y + box.height/2; return new Point (x, y); } Aliasing -------- Any time two variables refer to the same object, we say they are aliased. Any changes made to one object affect the other, too. Passing an object as a parameter creates a kind of aliasing. Reasons objects are good ------------------------ 1) Chunk related information together. Chunking overcomes human cognitive limitations. 2) Share information between methods in controlled ways. 3) Return more than one value from a method. Dangers of objects ------------------ 1) Don't forget that when you create an object variable, you don't get an object. 2) Beware the NullPointerException! 3) For primitive local variables, methods cannot interfere with each other -- they are encapsulated. Objects undermine encapsulation, allowing methods to interact in complex ways that can be confusing.