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

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

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.