JAVATM- The Beginnings

Passing and Returning Object References

Section 1- Passing an Object Reference to a Method

To pass an object to a method in Java, pass a reference variable which contains the address of the object to the method. This address is copied into the method’s parameter variable, which can then reference the fields and methods of the object.

In the example above, a Box object containing length=2, width=3, and height=4 resides at address 0x1000. The address of this Box object is assigned to reference variable b1. Since b1 is passed into method printBox, its value, address 0x1000,  is copied into parameter variable b. Parameter variable b now references the fields of the Box object, and it prints “length = 2 width = 3 height = 4”.

Another Box object containing length=5, width=6, and height=7 resides at address 0x2000. The address of this Box object is assigned to reference variable b2. Since b1 is passed into method

Copyright ©2017 by Ralph Lecessi Incorporated. All rights reserved.



Back to ralphlecessi.com