Java和c 传值引用_Java参数传递是传值还是传引用?

在Java的规范里说明了在Java中一切参数都是按值传递的,根本就没有引用传递这一说。

理解这个概念的关键是要明白:

Dog myDog;

这里声明的并不是一个Dog对象,而是一个指向Dog对象的指针。

这是什么意思呢,就是当你执行:

Dog myDog = new Dog("Rover");

foo(myDog);

本质上是你把创建好的Dog对象的地址传递给foo方法。(我说的‘本质上’其实是因为Java中的指针并不是直接的地址,不过可以简单的理解成这样)。

假设Dog对象在内存中的地址是42。那我们就是把42这个值传递给了foo方法。

public void foo(Dog someDog) {

someDog.setName("Max"); // AAA

someDog = new Dog("Fifi"); // BBB

someDog.setName("Rowlf"); // CCC

}

让我们来看看执行的时候会发生些什么。

someDog的值设置为42。

在AAA行

a.someDog指向一个内存地址为42的Dog对象。

b.把Dog(内存地址为42)对象的name属性改为Max。

在BBB行

a.一个新的Dog对象被创建,我们假设它的内存地址是74。

b.把这个74的内存地址值赋给someDog。

在CCC行

a.someDog指向一个内存地址为74的Dog对象。

b.把Dog(内存地址为74)对象的name属性改为Rowlf。

方法执行完毕。

现在让我们来想想在这个方法外面发生了什么:

myDog改变了吗?

这个问题的关键在于:

要明确myDog是一个指针,而不是一个实际的Dog对象。所以答案是它没有改变,myDog的值还是42;它指向的还是最开始的那个Dog对象(虽然在foo方法中的AAA行把它指向对象的name属性改成了Max,但是它指向的还是那个最初的Dog对象)。

这验证了改变所指对象的属性,但没有改变其指向。

Java的运行机制跟C很像。你可以给一个指针赋值,然后把这个指针传递给一个方法,之后在这个方法中你可以改变这个指针指向对象的数据,但是你不能改变这个指针的指向。

在C++,Ada,Pascal以及其他支持引用传递的语言中你可以直接改变传递的参数。如果Java是引用传递的话,那么在执行上面定义的foo方法的BBB行的时候someDog的指向就会被改变。

Let me explain this through an example:

public class Main{

public static void main(String[] args){

Foo f = new Foo("f");

changeReference(f); // It won't change the reference!

modifyReference(f); // It will modify the object that the reference variable "f" refers to!

}

public static void changeReference(Foo a){

Foo b = new Foo("b");

a = b;

}

public static void modifyReference(Foo c){

c.setAttribute("c");

}

}

I will explain this in steps:

1.Declaring a reference named f of type Foo and assign it to a new object of type Foo with an attribute "f".

Foo f = new Foo("f");

arXpP.png

2.From the method side, a reference of type Foo with a name a is declared and it's initially assigned to null.

public static void changeReference(Foo a)

k2LBD.png

3.As you call the method changeReference, the reference a will be assigned to the object which is passed as an argument.

changeReference(f);

1Ez74.png

4.Declaring a reference named b of type Foo and assign it to a new object of type Foo with an attribute "b".

Foo b = new Foo("b");

Krx4N.png

5.a = b is re-assigning the reference a NOT f to the object whose its attribute is "b".

rCluu.png

6.As you call modifyReference(Foo c) method, a reference c is created and assigned to the object with attribute "f".

PRZPg.png

7.c.setAttribute("c"); will change the attribute of the object that reference c points to it, and it's same object that reference f points to it.

H9Qsf.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值