-1

I have a class written for Fraction objects. I need to swap two Fraction objects, not the contents of the objects. Here is my code.

public void fswap(Fraction other){
    Fraction temp = other.copy();
    other = this;
    this = temp;

The copy() method returns a Fraction object identical to the object it was called on. The last line of this code throws an error in my IDE "cannot assign a value to final variable this". Any help is greatly appreciated.

1 Answers1

5

You cannot write a swap method in Java that swaps the objects, not their contents. It is literally impossible. This is a distinguishing feature of a pass-by-value language, though it's always important to remember that Java passes references by value.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • 1
    maybe worth noting that Java is in fact pass by value despite its ability to pass objects without copying. – djechlin Dec 04 '15 at 22:14