通过值/引用传递,是什么? [英] Pass by value/reference, what?
问题描述
该计划为6作为输出,但是当我取消对9号线,输出为5.为什么?我觉得b.a不应该改变,应该主要保持5。
1级C1 {
2 INT 1 = 5;3公共静态无效的主要(字符串ARGS []){
4 C1 B =新C1();
5 M1(B);
6的System.out.println(b.a);
7}8静态无效M1(C1 C){
9 // C = C1新();
10 C.A = 6;
11}
12}
当您在Java传递对象时,将会在由标记为B
引用意味着对象传递主
方法和 C
作为参数的方法 M1
,它们都指向同一个对象,因此,当您将值更改为6它就会体现在主
方法。
现在 C =新C1();
然后你做 C
来指向一个不同的对象,但 b
仍然指向你在你的主
方法创建的对象,因此更新值6不可见的主要方法,你会得到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 }
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.
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.
这篇关于通过值/引用传递,是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!