Java Reference
In-Depth Information
At this point, there are two Car objects in memory. The xyCar formal parameter references the new Car object
and not the one whose reference was passed to the method. Note that the actual parameter myCar still references the
Car object that you created in the main() method. The fact that the xyCar formal parameter references the new Car
object is indicated by the message labeled #3 in the output. When the test() method call returns, the main() method
prints details of the Car object being referenced by the myCar reference variable. See Listing 6-24.
Listing 6-24. An Example of a Pass by Reference Value
// PassByReferenceValueTest.java
package com.jdojo.cls;
public class PassByReferenceValueTest {
public static void main(String[] args) {
// Create a Car object and assign its reference to myCar
Car myCar = new Car();
// Change model, year and price of Car object using myCar
myCar.model = "Civic LX";
myCar.year = 1999;
myCar.price = 16000.0;
System.out.println("#1: model = " + myCar.model +
", year = " + myCar.year +
", price = " + myCar.price);
PassByReferenceValueTest.test(myCar);
System.out.println("#4: model = " + myCar.model +
", year = " + myCar.year +
", price = " + myCar.price);
}
public static void test(Car xyCar) {
System.out.println("#2: model = " + xyCar.model +
", year = " + xyCar.year +
", price = " + xyCar.price);
// Let's make xyCar refer to a new Car object
xyCar = new Car();
System.out.println("#3: model = " + xyCar.model +
", year = " + xyCar.year +
", price = " + xyCar.price);
}
}
#1: model = Civic LX, year = 1999, price = 16000.0
#2: model = Civic LX, year = 1999, price = 16000.0
#3: model = Unknown, year = 2000, price = 0.0
#4: model = Civic LX, year = 1999, price = 16000.0
 
Search WWH ::




Custom Search