SCJP 操作与赋值题目

来源:百度知道 编辑:UC知道 时间:2024/06/05 02:18:57
Given the following code, what will be the output?

class Value

{

public int i = 15;

}

public class Test

{

public static void main(String argv[])

{

Test t = new Test();

t.first();

}

public void first()

{

int i = 5;

Value v = new Value();

v.i = 25;

second(v, i);

System.out.println(v.i);

}

public void second(Value v, int i)

{

i = 0;

v.i = 20;

Value val = new Value();

v = val;

System.out.println(v.i + " " + i);

}

}

Choices:

a. 15 0

20

b. 15 0

15

c. 20 0

20

d. 0 15

20

答案是:
A is correct. When we p

因为对象是引用传递
first()方法将 属性i = 25 的 v对象的引用 传递给second()方法
second()方法中首先将这个 v 的属性 i 改为 20
然后让变量 v 指向新建的 val对象,second()方法中打印的是 val 的
属性 i(初始值15)
在first()方法中变量 v 指向的还是原来的对象,但已经被second()方法改为20,所以打印20

原理应该是这样
但具体表达可能有误