在我遇到这段代码之前,我以为我理解了变量范围:
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!!!
Run Code Online (Sandbox Code Playgroud)
编辑:我理解为什么a =新帐户(80)不会做任何事情,但我对a.deposit(5)实际工作感到困惑,因为a只是传入的原始帐户的副本...
变量a是传入的引用的副本,因此它仍然具有相同的值并且引用Account与account变量相同的对象(即,直到重新分配a).当您进行存款时,您仍在使用对外部范围中仍然引用的原始对象的引用.