以下是引用★王者至尊★在2006-5-6 12:51:00的发言:
选择下面这段代码的输出结果:
-----------------------------------------------------------------
class Test{
public int i=10; //instance variable,for every object of type Test there's a
//copy of i
}
public class ObParm{
public static void main(String argv[]){
ObParm o=new ObParm(); //invoke the constructor of ObParm
o.amethod(); //invoke the instance method with o
}
public void amethod(){
int i=99; //local variable,which will die once the method is
//finished
Test v=new Test(); //invoke the default constructor of Test
v.i=30; // instance variable v.i set to 30
another(v,i); //invoke another(Test v,int i)
System.out.println(v.i); //output
}
public void another(Test v, int i){
i=0; //another local variable with the same name with the local
//variable in amethod() and
//the instance variable in Test
v.i=20; //set v.i to 20.This value will last even when the method is finished
//because when we pass an object argument to a
//method the reference to the object is
//copied to the parameter,which will of course refer to the same object.
Test vh=new Test(); //invoke the default constructor of Test,which will automatically set i to 10
v=vh; //now v.i is 10 instead of 20,but we didn't not change the
//i in the original object
//Remember,it is the reference to the object that is copied to the method.
//So,you are just changing a copy of the reference to
//the original object here
//which will not change the original object at all!
System.out.println(v.i+" "+i); //output
}
}
----------------------------------------------------------
A 10,0,30
B 20,0,30
C 20,99,30
D10,0,20 is the answer
(不许运行哦!)
至于为什么会输出三个数字,请注意System.out.println(v.i+" "+i);是输出两个数字的
[此贴子已经被作者于2006-7-9 11:20:34编辑过]