java 传对象改变的是_方法传对象参数 改变不了引用 懵...求大神

这个问题产生的根源是,对于java中参数传递的误区:

原始类型按值传递;对象按引用传递。

其实不然。请记住,

java中,无论是原始类型还是对象,都是按值传递的。

这里的“值”可以简单的理解为“对象或原始类型在内存中的地址”(并不准确)。

插播两个概念,‘按值传递’和‘按引用传递’:

Pass-by-value:

The actual parameter (or argument expression) is fully evaluated and

the resulting value is copied into a location being used to hold the

formal parameter's value during method/function execution. That

location is typically a chunk of memory on the runtime stack for the

application (which is how Java handles it), but other languages could

choose parameter storage differently.

Pass-by-reference:

The formal parameter merely acts as an alias for the actual parameter.

Anytime the method/function uses the formal parameter (for reading or

writing), it is actually using the actual parameter.

不知如何翻译才不会有误解,便不翻了。逃)

回过头来看题主的问题,当调用

method(a,b);

时,是将a和b的地址传入方法method,那么

public static void method(Circle x,Circle y){

Circle tmp = x;

x = y;

y = tmp;

}

进入方法后,x初值为对象a的地址,y初值为对象b的地址;而进行交换后,只是将x指向了对象b的地址,y指向了对象a地址。而:

a和b的值并未交换。

好,现在再来看个例子:

Class User{

private String name;

.

.

.

}

public static void foo(User user){

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

user = new User("Fifi");// BBB

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

}

public static void main(String[] args){

User basicUser = new User("Rover");

foo(basicUser );

}

请问,‘AAA’、‘BBB’、‘CCC’这3行代码执行完后,对象basicUser的name分别是什么?

‘AAA’行:name为‘Max’;

‘BBB’行:name为‘Max’;

‘CCC’行:name为‘Max’;

请思考下原因。

Ps: 若有纰漏有误之处,欢迎批评指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值