DEV Community

Cover image for Passing Objects to Methods
Paul Ngugi
Paul Ngugi

Posted on

Passing Objects to Methods

Passing an object to a method is to pass the reference of the object. You can pass objects to methods. Like passing an array, passing an object is actually passing the reference of the object. The following code passes the myCircle object as an argument to the printCircle method:

  public class Test {
  public static void main(String[] args) {
  // CircleWithPrivateDataFields is defined in Listing 9.8
  CircleWithPrivateDataFields myCircle = new
  CircleWithPrivateDataFields(5.0);
  printCircle(myCircle);
  }

  public static void printCircle(CircleWithPrivateDataFields c) {
 System.out.println("The area of the circle of radius "
 + c.getRadius() + " is " + c.getArea());
 }
 }
Enter fullscreen mode Exit fullscreen mode

Java uses exactly one mode of passing arguments: pass-by-value. In the preceding code, the value of myCircle is passed to the printCircle method. This value is a reference to a Circle object.
The program below demonstrates the difference between passing a primitive type value and passing a reference value.

Image description

Radius Area
1.0 3.141592653589793
2.0 12.566370614359172
3.0 29.274333882308138
4.0 50.26548245743669
5.0 79.53981633974483
Radius is 6.0
n is 5

The CircleWithPrivateDataFields class is defined in the previous post. The program passes a CircleWithPrivateDataFields object myCircle and an integer value from n to invoke printAreas(myCircle, n) (line 11), which prints a table of areas for radii 1, 2, 3, 4, 5, as shown in the sample output.

Image description

Figure above shows the call stack for executing the methods in the program. Note that the objects are stored in a heap.

When passing an argument of a primitive data type, the value of the argument is passed. In this case, the value of n (5) is passed to times. Inside the printAreas method, the content of times is changed; this does not affect the content of n.

When passing an argument of a reference type, the reference of the object is passed. In this case, c contains a reference for the object that is also referenced via myCircle. Therefore, changing the properties of the object through c inside the printAreas method has the same effect as doing so outside the method through the variable myCircle. Pass-by-value on references can be best described semantically as pass-by-sharing; that is, the object referenced in the method is the same as the object being passed.

Top comments (0)