Page 281 - Introduction to Programming with Java: A Problem Solving Approach
P. 281
Let’s now examine this code in detail one statement at a time. Statement 1:
The first statement is a variable declaration for the car1 reference variable. It allocates space in memory for the car1 reference variable—just the reference variable itself, not an object. Eventually, the car1 reference variable will hold the address of an object, but since there’s no object created
for it yet, it doesn’t yet hold a legitimate address. What’s the default value for a reference variable? It depends. If the reference variable is defined locally within a method (that is, it’s a local variable), then it gets garbage initially. If it’s defined at the top of a class, above all the method definitions (that is, it’s an instance variable), then it gets initialized to null. Since Statement 1 doesn’t have an access modifier (private), we can assume it’s a local variable. So car1 will contain garbage by default, and that’s what this picture indicates:
reference
Statement 2:
The second statement’s new operator allocates space in memory for a new Car object. The assignment operator assigns the address (memory location) of the allocated space to the car1 reference variable. Don’t forget this operation. Forgetting to instantiate is a common beginner’s error.
car1
car1
Apago PDF Enhancer
reference object
car1
The third statement uses the car1 variable’s value (the address of a Car object) to find a particular Car object in memory. Once that Car object is found, 1998 is assigned into it. More specifically, 1998 is assigned into the year instance variable portion of that Car object. Normally, we’d use a method to assign 1998 into car1’s year instance variable. In the interest of simplification for clarity’s sake, we avoided the method call by assuming that year is a public instance variable.
reference object
7.2 Object Creation – A Detailed Analysis 247
?
make
year color
0
nul1
Statement 3:
nul1
make
year color
1998
nul1
nul1