You have a scope problem.
Each method defines its arguments as their own references. The values passed in are assigned to the references defined in the method signature. The method signature is essentially a declaration of local variables that are assigned values when the method is called. This what the other answers mean by 'pass by value'.
private static Cat cat1; // < this cat1 and cat2 are
private static Cat cat2; // never referred to
public static void change(Cat cat1, Cat cat2) {
Cat temp = cat1; // ^ ^
cat1 = cat2; // < cat1--' |
cat2 = temp; // < cat2 means------'
}
If it helps, you could think about it like this:
// pseudo code
method change() {
Cat cat1 = method.Argument[0];
Cat cat2 = method.Argument[1];
...
}
By writing to cat1 and cat2, you are simply writing to the local variables defined as part of the method signature. You are not writing to the identically named static scoped variables.
To make the code work, you can explicitly refer to the static values.
public static void change(Cat cat1, Cat cat2) {
Cat.cat1 = cat2; // cat1 and cat2 are static
Cat.cat2 = cat1; // i.e. defined on the class
}
Or you could rename them.
public static void change(Cat c1, Cat c2) {
cat1 = c2;
cat2 = c1;
}
Or, since they are static, you could just do away with the method arguments altogether.
public static void change() {
Cat temp = cat1;
cat1 = cat2;
cat2 = temp;
}
Notice that only the final one still required the temp
variable.