CS231 lecture notes, Fall 1998 Week 1, Friday Reading Standish Chapter 3.1 to 3.4 Section 3.3 -- review of implicit pointers Allocation 1) primitive types, when you declare them, you get allocated space 2) Object types, when you declare them you get a reference initialized to null no object allocated -- have to allocate explicitly using new or, for some objects, literals int x = 0; double y = 0.0; String s = "fred"; String s = new String ("fred"); Rectangle r = new Rectangle (); Rectangle r = new Rectangle (0, 0, 10, 20); 3) Accessing the fields of an object has the effect of dereferencing the reference. Cannot access the fields of a null object. Causes NullPointerException. Assignment 1) assignment of primitive types copies data 2) assignment of Object types copies references two references to the same object -- aliasing sometimes called a shallow copy Deep copying 1) usually done with a copy constructor public Rectangle (Rectangle r); creates a new object Rectangle r = new Rectangle (0, 0, 10, 20); Rectangle s = new Rectangle (r); s.x = 10; System.out.println (r.x); prints 0 Testing equality 1) shallow equality = pointer equality Do these pointers point to the same object? Rectangle r = new Rectangle (0, 0, 10, 20); Rectangle s = new Rectangle (r); if (r == s) is false! Not the same object, although the contents are the same 2) deep equality can mean all fields are equal, or might mean something application-specific a) default method of all objects called equals, and the default behavior is shallow equality b) many classes override equals to provide different behavior. For example, the equals method of the Rectangle class does deep equality r.equals (s) is true! c) For some application, we might want rectangles to be considered equal if their widths and heights are the same, regardless of position. We can do that by creating a new class that inherits from Rectangle, and overriding the definition of equals. (more about inheritance soon) That goes for Strings, too. 1) == for strings means, are these two Strings stored in the same location? Are they the same object. That's not usually what we mean. 2) equals does the right thing String s = "fred"; String r = "fred"; (s == r) not strictly true (although the issue is confounded) s.equals (r) definitely true Never use == to compare Strings (oops -- I think I did this last semester). Go over the List.java and ListNode.java examples. Develop deleteLastNode as an in class exercise (page 85-86 of Standish).