简体   繁体   English

Java中的方法的可变范围

[英]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 original Account being passed in... 编辑:我知道为什么a = new Account(80)不会做任何事情,但是我对a.deposit(5)实际工作感到困惑,因为a只是传入的原始帐户的副本...

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 ). 变量a传入的引用的副本 ,因此它仍然具有相同的值,并且与account变量引用相同的Account对象(也就是说,直到您重新分配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. 进行存款时,您仍在使用对原始对象的引用,该对象在外部范围中仍被引用。

您可能需要阅读有关Java中的值传递的更多信息。

Just may be to make it clear, All variables passed by value means that the called method just gets the values of parameters and not a reference (pointer) to these objects, so any modification on these objects in the method body doesn't affect the outer object. 为了清楚起见,所有通过值传递的变量意味着被调用的方法仅获取参数的值,而不是对这些对象的引用(指针),因此在方法主体中对这些对象的任何修改均不会影响外物。 Unlike c++ which has the option to pass the object by reference where the method gets the actual object not it's value, so any modification in the method body affects the outer object.Java doesn't have pass by reference. 与c ++不同,它具有通过引用传递对象的选项,其中方法获取实际对象而不是其值,因此方法主体中的任何修改都会影响外部对象.Java没有通过引用传递。

在Java中,变量按值传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM