View RSS Feed

Java Object

Passing Reference Data Type Arguments

Rate this Entry
by , 04-26-2012 at 05:23 PM (1796 Views)
Reference data type parameters also get passed by the value into methods. It shows that by returning methods, same objects are referred by the passed in reference. But, the objectís field value might get changed in case there is a proper access level.

Let us take a method into consideration present in arbitrary class, which will be moving the Circle objects.
Java Code:
public void moveCircle(Circle circle, int deltaX, int deltaY) {
    // code to move origin of 
    // circle to x+deltaX, y+deltaY
    circle.setX(circle.getX() + deltaX);
    circle.setY(circle.getY() + deltaY);
    // code to assign a new 
    // reference to circle
    circle = new Circle(0, 0);
Invoke the method with these given arguments.
Java Code:
moveCircle(myCircle, 23, 56)
Initially, circle usually would be referring to myCircle, inside the method. X and Y coordinates are changed by the method which circle references to be 23 & 56 respectively. There will be persistent changes, when method returns. A reference is then assigned to circle(to new circle object, with x = y = 0 ). No permanence is there for this reassignment as reference canít be changed and is passed by value. Object which is pointed by the circle gets changed within the method. But, when method is returned, same Circle object is referenced by the myCircle, just they way method had been called before.

Submit "Passing Reference Data Type Arguments" to Facebook Submit "Passing Reference Data Type Arguments" to Digg Submit "Passing Reference Data Type Arguments" to Submit "Passing Reference Data Type Arguments" to StumbleUpon Submit "Passing Reference Data Type Arguments" to Google