CS231 lecture notes, Fall 1998 Week 6, Friday Review of Java object handout. Object variables contain references. Two kinds of types. Different semantics. new is the only way to create a new object. 1) Java implicitly creates space; i.e. new instance variables 2) the constructor gets invoked. Primary job -- initialize instance vars 3) Java implicitly returns a reference to the new object Assignment: copies references, not objects Aliasing: more than one reference to the same object Operators don't generally work on objects (except String concat). Only one object literal (null). Belongs to all types, even the ones it doesn't deserve to. Cast: any object can be an Object Casting can create a weird kind of aliasing. Class: a template for creating new object. Instance variables complete the sentence "Every has a ..." Instance: every object is an instance of some class Instance variable: syntax (outside all methods, no static) Global variable: outside all methods, static. I never want to see the word final on another exam (except the final). Local variable: inside a method. Method: two kinds of methods, object and class. Object methods -------------- When you invoke an object method, you invoke it on an object. That object becomes the current object, called "this". Inside the method, all references to instance variables refer to the instance variables of the current object. Inside a method, if you invoke an object method, it is implicitly invoked on the current object. Class methods ------------- Class methods are not invoked on objects, and they do not have a current object. From within their own class definitions, they can be invoked by name; from outside, they have to be qualified, as in Math.cos(x). Sometimes I refer to this as "invoking the method on a class," although that is not strictly accurate. Reading: Standish Chapter 6.1 -- 6.6 Stackness, continued Sometimes you can use your own stack to speed up recursive implementations by making them iterative: public static int totalTree2 (Tree root) { Stack stack = new Stack (); if (root != null) stack.push ((Object) root); Tree tree; int total = 0; while (!stack.empty()) { tree = (Tree) stack.pop (); // how do I know the popped item is not null? total += tree.value; if (tree.right != null) stack.push ((Object) tree.right); if (tree.left != null) stack.push ((Object) tree.left); } return total; } But it is generally not a good idea, since the performance improvement is likely to be small, and the iterative version is much more difficult to prove correct.