Problem - returning correct value from an class method - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Problem - returning correct value from an class method

RibbletonRibbleton Posts: 152Member
[b][red]This message was edited by Ribbleton at 2005-3-3 10:25:41[/red][/b][hr]
The problem is, when i return from 'mySetXY.setX(x);' how come the x or y value are not set to 250 (XY_START_POS). I pass them into the method 'mySetXY.setX(x);' why wont they return;

class BallGame extends JApplet{ // this applet

class Ball extends Thread implements Runnable{
private SetXY mySetXY;

public Ball(int xin,int yin)
{
// contains other stuff


mySetXY = new SetXY();
}
public void run() // Other stuff in here
{
mySetXY.setX(x);
mySetXY.setY(y);
}

class SetXY
{
final int XY_START_POS = 250;

public int setX(int posX)
{
posX = XY_START_POS;
return posX;
}

public int setY(int posY)
{
posY = XY_START_POS;
return posY;
}
} // end SetXY
} // end Ball
} // end BallGame

thanks for your time.

*Ribbleton_


Comments

  • ninchagoraninchagora Posts: 82Member
    [code]
    : public void run() // Other stuff in here
    : {
    : mySetXY.setX(x);
    : mySetXY.setY(y);
    : }
    :
    : class SetXY
    : {
    : final int XY_START_POS = 250;
    :
    : public int setX(int posX)
    : {
    : posX = XY_START_POS;
    : return posX;
    : }
    [/code]

    If a parameter is of primitive type (like [b]int[/b]) it is passed by value.
    You can modify it inside the method, but the changes won't reflect to the actual argument given (because you could call it with [b]setX(2+4*3)[/b] as well - only the value matters).

    Method [b]setX[/b] returns new value of [b]posX[/b] correctly, but you would have to write:
    [b]x = mySetXY.setX(x); [/b]

    Now, argument [b]posX[/b] has no use, because you've overwritten it with [b]posX = XY_START_POS;[/b]- you could just write [b]return XY_START_POS;[/b]


    The other thing is if parameter is an object of some class (which is passed by reference).
    If you change its fields, the changes are performed upon the object itself, and will be visible in the object given when you return from the method.



Sign In or Register to comment.