Topic 3 References and Object Variables Thou shalt
Topic 3 References and Object Variables "Thou shalt not follow the NULL pointer, for chaos and madness await thee at its end. " - Henry Spencer CS 307 Fundamentals of Computer Science References and Object Variables 1
Object Variables 8 object variables are declared by stating the class name / data type and then the variable name – same as primitives – in Java there are hundreds of built in classes. • show the API page – don't learn the classes, learn how to read and use a class interface (the users manual) 8 objects are complex variables. – They have an internal state and various behaviors that can either change the state or simply tell something about the object CS 307 Fundamentals of Computer Science References and Object Variables 2
Object Variables public void object. Varaiables() { Rectangle rect 1; Rectangle rect 2; // 2 Rectangle objects exist? ? // more code to follow } 8 So now there are 2 Rectangle objects right? 8 Not so much. 8 Object variables in Java are actually references to objects, not the objects themselves! – object variables store the memory address of an object of the proper type not an object of the proper type. – contrast this with primitive variables CS 307 Fundamentals of Computer Science References and Object Variables 3
The Pointer Sidetrack 8 IMPORTANT!! This material may seem a bit abstract, but it is often the cause of many a programmers logic error 8 A pointer is a variable that stores the memory address of where another variable is stored 8 In some languages you can have bound variables and dynamic variables of any type – a bound variable is one that is associated with a particular portion of memory that cannot be changed 8 Example C++, can have an integer variable or a integer pointer (which is still a variable) int. Var; // a int var int * int. Ptr; //pointer to an int var CS 307 Fundamentals of Computer Science References and Object Variables 4
Pointer Variables in C++ int. Var = 5; // a int var int * int. Ptr; //pointer to an int var int. Ptr = new int; /* dynamically allocate an space to store an int. Ptr holds the memory address of this space*/ 5 int. Var CS 307 Fundamentals of Computer Science ? ? 0 x 00122155 int. Ptr References and Object Variables ? ? space for an int in memory assume memory address 0 x 00122155 5
Pointer Complications 8 C++ allows actual variables and pointers to variables of any type. Things get complicated and confusing very quickly int. Var = 5; // a int var int * int. Ptr; //pointer to an int var int. Ptr = new int; // allocate memory *int. Ptr = 12; /* assign the integer being pointed to the value of 12. Must dereference the pointer. i. e. get to the thing being pointed at*/ cout << int. Ptr << "t" << *int. Ptr << "t" << &int. Ptr << endl; // 3 different ways of manipulating int. Ptr 8 In C++ you can work directly with the memory address stored in int. Ptr – increment it, assign it other memory addresses, pointer “arithmetic” CS 307 Fundamentals of Computer Science References and Object Variables 6
Attendance Question 1 Given the following C++ declarations how would the variable int. Ptr be made to refer to the variable int. Var? int. Var = 5; int. Ptr = new int; A. int. Ptr = int. Var; B. int. Ptr = *int. Var; C. *int. Ptr = int. Var; D. int. Ptr = &int. Var; E. int. Ptr = int. Var; CS 307 Fundamentals of Computer Science References and Object Variables 7
And Now for Something Completely Different… 8 Thanks Nick… 8 Link to Bink CS 307 Fundamentals of Computer Science References and Object Variables 8
Benefit of Pointers 8 Why have pointers? 8 To allow the sharing of a variable – If several variables(objects, records, structs) need access to another single variable two alternatives 1. keep multiple copies of variable. 2. share the data with each variable keeping a reference to the needed data other ptr data not shown other data ptr not shown sharer 2 CS 307 Fundamentals of Computer Science shared variable References and Object Variables sharer 1 9
Time Space Trade Off 8 Often the case that algorithms / solutions an be made faster by using more space (memory) or can use less space at the expense of being slower. BAD space used GOOD time to complete CS 307 Fundamentals of Computer Science References and Object Variables 10
More Benefits 8 Allow dynamic allocation of memory – get it only when needed (stack memory and heap memory) 8 Allow linked data structures such as linked lists and binary trees – incredibly useful for certain types of problems 8 Pointers are in fact necessary in a language like Java where polymorphism is so prevalent (more on this later) 8 Now the good news – In Java most of the complications and difficulties inherent with dealing with pointers are removed by some simplifications in the language CS 307 Fundamentals of Computer Science References and Object Variables 11
Dynamic Memory Allocation Your program has two chunks of memory to work with: Stack memory (or the runtime Stack) and Heap memory When a Java program starts it receives two chunks of memory one for the Stack and one for the Heap. Things that use Stack memory: local variables, parameters, and information about methods that are in progress. Things that use Heap memory: everything that is allocated using the new operator. CS 307 Fundamentals of Computer Science References and Object Variables 12
The Picture Stack Memory x y s Heap Memory String Object my. Chars He l l o void toy. Code. For. Memory(int x) { int y = 10; x += y; String s = new String ("Hello"); System. out. println(x + " " + y + s); } CS 307 Fundamentals of Computer Science References and Object Variables 13
How Much Memory? How big is the Heap? System. out. println("Heap size is " + Runtime. get. Runtime(). total. Memory()); How much of the Heap is available? System. out. println("Available memory: " + Runtime. get. Runtime(). free. Memory()); CS 307 Fundamentals of Computer Science References and Object Variables 14
References in Java 8 In Java all primitive variables are value variables. (real, actual, direct? ) – it is impossible to have an integer pointer or a pointer to any variable of one of the primitive data types 8 All object variables are actually reference variables (essentially store a memory address) to objects. – it is impossible to have anything but references to objects. You can never have a plain object variable CS 307 Fundamentals of Computer Science References and Object Variables 15
Back to the Rectangle Objects 8 rect 1 and rect 2 are variables that store the memory addresses of Rectangle objects 8 right now they are uninitialized and since they are local, variables may not be used until they are given some value public void object. Varaiables() { Rectangle rect 1; Rectangle rect 2; // rect 1 = 0; // syntax error, C++ style // rect 1 = rect 2; // syntax error, unitialized rect 1 = null; // pointing at nothing rect 2 = null; // pointing at nothing } 8 null is used to indicate an object variable is not pointing / naming / referring to any Rectangle object. CS 307 Fundamentals of Computer Science References and Object Variables 16
Creating Objects 8 Declaring object variables does not create objects. – It merely sets aside space to hold the memory address of an object. – The object must be created by using the new operator and calling a constructor for that object public void object. Varaiables() { Rectangle rect 1; rect 1 = new Rectangle(); Rectangle rect 2 = new Rectangle(5, 10, 20, 30); // (x, y, width, height) } // rect 1 and rect 2 now refer to Rectangle objects 8 For all objects, the memory needed to store the objects, is allocated dynamically using the new operator and a constructor call. (Strings are a special case. ) – constructors are similar to methods, but they are used to initialize objects CS 307 Fundamentals of Computer Science References and Object Variables 17
The Yellow Sticky Analogy Rectangle Object rect 1 x: 0 y: 0 width: 0 height: 0 Rectangle Object rect 2 CS 307 Fundamentals of Computer Science x: 5 y: 10 width: 20 height: 30 References and Object Variables 18
8 Is this easier? Pointers in Java – primitives one thing, objects another? 8 can't get at the memory address the pointer stores as in C++ although try this: Object obj = new Object(); System. out. println( obj. to. String() ); 8 dereferencing occurs automatically 8 because of the consistency the distinction between an object and an object reference can be blurred – "pass an object to the method" versus "pass an object reference to the method 8 Need to be clear when dealing with memory address of object and when dealing with the object itself CS 307 Fundamentals of Computer Science References and Object Variables 19
Working with Objects 8 Once an object is created an object variable points to it then Object may be manipulated via its methods Rectangle r 1 = new Rectangle(); r 1. resize(100, 200); r 1. set. Location(10, 20); int area = r 1. get. Width() * r 1. get. Height(); Rectangle r 2 = null; r 2. resize( r 1. get. Width(), r 1. get. Height() * 2 ); // uh-oh! 8 Use the dot operator to deference an object variable and invoke one of the objects behaviors 8 Available behaviors are spelled out in the class of the object, (the data type of the object) CS 307 Fundamentals of Computer Science References and Object Variables 20
What's the Output? public void object. Variables() { Rectangle rect 1 = new Rectangle(5, 10, 15, 20); Rectangle rect 2 = new Rectangle(5, 10, 15, 20); ; System. out. println("rect 1: " + rect 1. to. String() ); System. out. println("rect 2: " + rect 2. to. String() ); // Line 1 System. out. println("rect 1 == rect 2: " + (rect 1 == rect 2)); rect 1 = rect 2; rect 2. set. Size(50, 100); // (new. Width, new. Height) // Line 2 System. out. println("rect 1: " + rect 1. to. String() ); System. out. println("rect 2: " + rect 2. to. String() ); System. out. println("rect 1 == rect 2: " + (rect 1 == rect 2)); int x = 12; int y = 12; // Line 3 System. out. println("x == y: " + (x == y) ); x = 5; y = x; x = 10; System. out. println("x == y: " + (x == y) ); // Line 4 System. out. println("x value: " + x + ", y value: " + y); } CS 307 Fundamentals of Computer Science References and Object Variables 21
Attendance Question 2 What is output by the line of code marked Line 1? A. rect 1 == B. rect 1 == C. rect 1 == D. int. Ptr = E. rect 1 == CS 307 Fundamentals of Computer Science rect 2: true rect 2: rect 1 == rect 2: false &int. Var; rect 2: 0 References and Object Variables 22
Attendance Question 3 What will be the width and height of the Rectangle object rect 1 refers to at the line of code marked Line 2? A. width = 15, height = 20 B. width = 20, height = 15 C. width = -1, height = -1 D. width = 0, height = 0 E. width = 50, height = 100 CS 307 Fundamentals of Computer Science References and Object Variables 23
Attendance Question 4 What is output by the line of code marked Line 3? A. x B. x C. x D. x E. x == == == y: y: y: CS 307 Fundamentals of Computer Science 0 1 true x == y false References and Object Variables 24
Attendance Question 5 What is output by the line of code marked Line 4? A. x B. x C. x D. x E. x value: value: CS 307 Fundamentals of Computer Science 5, y value: 5 10, y value: 5 0, y value: 0 5, y value: 10; 10, y value: 10 References and Object Variables 25
Equality versus Identity A man walks into a pizza parlor, sits down, and tells the waiter, "I'll have what that lady over there is eating. " The waiter walks over to the indicated lady, picks up the pizza that is resting in front of her, and sets it back down in from of the man's table. 8 confusion over equality and identity 8 identity: two things are in fact the same thing 8 equality: two things are for all practical purposes alike, but not the exact same thing 8== versus the. equals method – use the. equals method when you want to check the contents of the pointee, use == when you want to check memory addresses CS 307 Fundamentals of Computer Science References and Object Variables 26
Just Like the Real World 8 Objects variables are merely names for objects 8 Objects may have multiple names – meaning there are multiple object variables referring to the same object (sharing) Professor Scott (Ha Ha) Michael! Mike Mr. Scott dada Daddy CS 307 Fundamentals of Computer Science References and Object Variables 27
The Garbage Collector Rectangle rect 1 = new Rectangle(2, 4, 10); Rectangle rect 2 = new Rectangle(5, 10, 20, 30); // (x, y, width, height) rect 1 = rect 2; /* what happened to the Rectangle Object rect 1 was pointing at? */ 8 If objects are allocated dynamically with new how are they deallocated? – delete in C++ 8 If an object becomes isolated (no longer is in scope), that is has no references to it, it is garbage and the Java Virtual Machine garbage collector will reclaim this memory AUTOMATICALLY! CS 307 Fundamentals of Computer Science References and Object Variables 28
Objects as Parameters 8 All parameters in Java are value parameters 8 The method receives a copy of the parameter, not the actual variable passed 8 Makes it impossible to change a primitive parameter 8 implications for objects? (which are references) – behavior that is similar to a reference parameter, with a few minor, but crucial differences – "Reference parameter like behavior for the pointee. " CS 307 Fundamentals of Computer Science References and Object Variables 29
Immutable Objects 8 Some classes create immutable objects 8 Once created these objects cannot be changed – note the difference between objects and object variables 8 Most immediate example is the String class 8 String objects are immutable 8 Why might this be useful? String name = "Mike"; String same. Name = name; name += " " + "David" + "Scott"; System. out. println( name ); System. out. println( same. Name ); CS 307 Fundamentals of Computer Science References and Object Variables 30
- Slides: 30