Pass by value/reference, what?(按值/引用传递,什么?)
问题描述
这个程序输出 6,但是当我取消注释第 9 行时,输出是 5.为什么?我认为 b.a 不应该改变,应该保持 5 为主.
This program gives 6 as output, but when I uncomment the line 9, output is 5. Why? I think b.a shouldn't change, should remain 5 in main.
1 class C1{
2 int a=5;
3 public static void main(String args[]){
4 C1 b=new C1();
5 m1(b);
6 System.out.println(b.a);
7 }
8 static void m1(C1 c){
9 //c=new C1();
10 c.a=6;
11 }
12 }
推荐答案
当你在 Java 中传递对象时,它们作为引用传递,意思是 b
在 main
方法中引用的对象和 c
作为方法 m1
中的参数,它们都指向同一个对象,因此当您将值更改为 6 时,它会反映在 main
方法.
When you pass object in Java they are passed as reference meaning object referenced by b
in main
method and c
as argument in method m1
, they both point to the same object, hence when you change the value to 6 it gets reflected in main
method.
现在,当您尝试执行 c = new C1();
时,您使 c
指向不同的对象,但 b
是仍然指向您在 main
方法中创建的对象,因此更新后的值 6 在 main 方法中不可见,您得到 5.
Now when you try to do c = new C1();
then you made c
to point to a different object but b
is still pointing to the object which you created in your main
method hence the updated value 6 is not visible in main method and you get 5.
这篇关于按值/引用传递,什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按值/引用传递,什么?


- C++ 和 Java 进程之间的共享内存 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01