import uwcse.graphics.*;
import java.awt.Color;
/**
* A class to illustrate the 'call by value' concept
* Write two methods:
* - changeSign(int someInt) to change the sign of someInt
* - changeColor(Rectangle r) to change the color of r
*
* Call both of these methods from another method. See which one
* has an effect within that other method.
*/
public class CallByValue {
/**
* Call 2 methods: one method takes a primitive type, the other a reference
* type. See the difference.
*/
public void callByValueExamples() // complete
{
// A method cannot modify the value of an actual parameter
// if the actual parameter is a primitive type
// Can't change the sign of i in the method changeSign
int i = 10;
System.out.println("Before changeSign: " + i);
changeSign(i); // i is the primitive type
System.out.println("After changeSign: " + i);
// But a method can change the content of an object
// passed as a reference
Rectangle r = new Rectangle();
r.setColor(Color.red);
System.out.println("Before changeColor: " + r.getColor());
changeColor(r); // r is a reference to an Rectangle
System.out.println("After changeColor: " + r.getColor());
}
/**
* Change the sign of the integer
*/
private void changeSign(int someInt) {
// change the sign of the formal parameter
someInt = -someInt;
}
/**
* change the color of the Rectangle to green
*/
private void changeColor(Rectangle r) {
// Set the color to green
r.setColor(Color.green);
}
/**
* Starts the application
*/
public static void main(String[] args) {
new CallByValue().callByValueExamples();
}
}