Here is an example of a method with an object reference variable as parameter:
public static void main(String[] args)
{
Circle circle1 = new Circle(1);
Circle circle2 = new Circle(4);
printCircle(circle1); // Pass object as argument
printCircle(circle2); // Pass object as argument
}
// Method with an object as parameter
public static void printCircle( Circle c )
{
System.out.println("The area of the circle of radius "
+ c.radius + " is " + c.getArea());
}
|
In Java, the object reference in the actual parameter is copied to the object reference argument
|
Since the formal parameter is an alias for the actual parameter, the original object will be updated:
public static void main(String[] args)
{
Circle circle1 = new Circle(1);
System.out.println( circle1.getArea() ); // 3.14159
incrementRadius( circle1 ); // increment radius by 1
System.out.println( circle1.getArea() ); // 4 × 3.14159
}
// Method updates object passed as parameter
public static void incrementRadius( Circle c )
{
c.radius++; // Increment radius by 1
}
|
In Java, the formal parameter c is an alias of the actual parameter circle1
So c.radius++ will also updates circle1.radius
|
|
|
Demo program that shows that arguments as passed to method by copying the value:
public static void main(String[] args)
{
int x;
x = 4;
System.out.println(x);
increment( x ); // Pass x by copying: a = x
System.out.println(x);
}
public static void increment(int a )
{
a = a + 1;
}
|
Demo with BlueJ: show the activation record of main( ) and increment( ) when stopped in increment( )