Could someone explain why this prints 15 and not 0? From what I am understanding, when passBall is called, it is called with ball as its parameter and when catchBall is called with ball also as its parameter, so when we are in catchBall, we have a reference to ball (the original ball from playGame) and so what I don't understand is when ball = newBall in catchBall, why doesn't ball.getSpeed() equal to 0 when we reach the print statement in playGame()?
public static void main(String[] args) {
Game g = new Game();
g.playGame();
}
public class Ball {
private int speed;
// This creates a ball with the given speed
public Ball() {
}
//This sets the speed of the ball to the given speed
public void setSpeed(int speed) {
this.speed = speed;
}
//This returns the speed of the ball
public int getSpeed() {
return speed;
}
}
public class Game {
public void playGame() {
Ball ball = new Ball();
ball.setSpeed(10);
passBall(ball);
System.out.println(ball.getSpeed());
}
public void passBall(Ball ball) {
Ball newBall = ball;
ball.setSpeed(ball.getSpeed() + 5);
catchBall(ball);
}
public void catchBall(Ball ball) {
Ball newBall = new Ball();
newBall.setSpeed(40);
newBall.setSpeed(0);
ball = newBall;
}
}