CSC231 Java passes objects by reference
--D. Thiebaut 10:11, 12 November 2012 (EST)
Example Java Program
This program defines a class for a simple object that contains 2 int members, x and y. It passes the object to a function, modif(), that doubles x and triples y.
public class ReferenceExample {
int x;
int y;
ReferenceExample( int a, int b ) {
x = a;
y = b;
}
public String toString() {
return String.format( "x = %d y = %d", x, y );
}
/**
* @param args
*/
public static void main(String[] args) {
ReferenceExample A = new ReferenceExample( 10, 2 );
System.out.println( "A = " + A );
modif( A );
System.out.println( "A = " + A );
}
public static void modif( ReferenceExample R ) {
R.x = R.x * 2;
R.y = R.y * 3;
}
}
Output
A = x = 10 y = 2
A = x = 20 y = 6