Variable scope with a method in Java
I thought I understood variable scope until I came across this bit of code:
private static void someMethod(int i, Account a) {
i++;
a.deposit(5);
a = new Account(80);
}
int score = 10;
Account account = new Account(100);
someMethod(score, account);
System.out.println(score); // prints 10
System.out.println(account.balance); // prints 105!!!
EDIT: I understand why a=new Account(80) would not do anything but I'm confused about a.deposit(5) actually working since a is just a copy of the origin开发者_StackOverflow中文版al Account being passed in...
The variable a
is a copy of the reference being passed in, so it still has the same value and refers to the same Account
object as the account
variable (that is, until you reassign a
). When you make the deposit, you're still working with a reference to the original object that is still referred to in the outer scope.
It might be time for you to read more about pass-by-value in Java.
In java, variables are passed by value.
精彩评论