0

I am starting to learn Java and I am struggling trying to understand why in this situation, the account money doesn't change to 5.

Trying with code I have realized that inside the method manipulate() the money of c1 actually changes but when returns to the main, it just increases and doesn't get the value of c2 (guess it is something about memory directions).

I am little familiarized with C and I understand it must be something like using a parameter with or without pointer but as this is OOP, I cant understand it. Could someone explain me easily?

public class Account {
    private int money;
    
    public Account(int money){
        this.money=money;
    }
    
    public static void manipulate(Account c1){
        c1.add(120);
        Account c2 = new Account(5);
        c1 = c2;
    }
    
    public void add(int money){
        this.money += money;
    }
    
    public int actual_money(){
        return this.money;
    }
    
    public static void main(String args[]) {
        
      Account c1 = new Account(100);

      manipulate(c1);
      
      System.out.println("Money = " + c1.actual_money()); //prints 220
    }
}
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
rascadux
  • 56
  • 6
  • 2
    `c1 = c2` has no effect because you are overwriting a local parameter. Java is not C or C# in this regard and can't overwrite the original reference from within the method. – akarnokd Jun 16 '22 at 15:46
  • 1
    @akarnokd, c# behaves exactly the same way as java by default, but you can pass the parameter by reference using ref keyword – Vladimir Efimenko Jun 16 '22 at 15:49
  • 1
    @VladimirEfimenko I know but didn't want to confuse the OP with syntax not existing in Java. – akarnokd Jun 16 '22 at 15:51
  • 1
    It has nothing to do with OOP, this is how parameters are passed to the methods, the c1 is a copy of a reference you pass to the method – Vladimir Efimenko Jun 16 '22 at 15:52
  • And C would behave the same if you passed an Account pointer to a function and then reassigned the pointer to point to a different Account struct within the function. The reason in all three cases is that you are passing a pointer (or a reference) by *value* and assigning a different value to the parameter has no effect on the caller. – David Conrad Jun 16 '22 at 16:15
  • The title of your Question here should be a summary of your specific technical issue. – Basil Bourque Jun 16 '22 at 16:24

0 Answers0