java is passing by reference.
t.change(a); //passing reference of a to the argument of change(Actor a);
...inside change()
a=new SadActor(); //copy reference of SadActor to local varible a; this a is not
//the same object with a=new HappyActor();
...outside change()
a still refers to the original obejctvoid change(Actor b){ b=new SadActor()} may make you feels better
t.change(a); //passing reference of a to the argument of change(Actor a);
...inside change()
a=new SadActor(); //copy reference of SadActor to local varible a; this a is not
//the same object with a=new HappyActor();
...outside change()
a still refers to the original obejctvoid change(Actor b){ b=new SadActor()} may make you feels better
void change(Actor a){a = new SadActor();}
改为
void change(){this.a = new SanActor();}t.change(a);
改为
t.change();
不过《Java编程思想》上给出的原例子中Stage类中,
有一句void change() {a = new SadActor();}
这里面所定义的a=new SadActor同样应该只在change()内部生效,但是,为什么整个程序的执行结果却是
HappyActor.play()
SadActor.play()呢,这不是说明,change()函数实际上改动了函数外的a吗?___________________________________________________________________
附:《Java编程思想》给出的原程序:
abstract class Actor{
abstract void act();
}
class HappyActor extends Actor{
void act(){
System.out.println("HappyActor");
}
}
class SadActor extends Actor{
void act(){
System.out.println("SadActor");
}
}
class Stage{
Actor a = new HappyActor();
void change() { a = new SadActor();}
void go(){a.act();}
}
public class Transmogrify{
public static void main(String[] args){
Stage s = new Stage();
s.go();
s.change();
s.go();
}
}
看了你的第一次回复,按照你所说的:
...inside change()
a=new SadActor(); //copy reference of SadActor to local varible a; this a is not
//the same object with a=new HappyActor();
...outside change()
a still refers to the original obejct
我还以为我明白了,可是看了你的第二次回复:
a=new SadActor(); //here a is the class field a of Stage class, not the local var
才发现自己还是不太清楚,为什么这个时候的a,又不是local var 了啊?
里面的a才是local variable。
而你的a申明在Transmogrify
所以a属于Transmogrify而不是change
例如:
public void a()
{
XXX b = xxx; //这个是内部变量;
b = xxx;//这个是成员变量;
}
public class a
{
public static int b = 5;
public void c(int b)
{
System.out.println(b); //先看一下传进来的参数值
b = 10;
System.out.println(b);//载看改变后的参数值
} public static void mani(String[] args)
{
int d = 30;
a f = new a();
System.out.println(b);//先看一下成员变量改变没有.
a.c(d);
System.out.pritnln(d);//在看一下传入的参数改变没有 答案是没有改变.
System.out.println(b);//再看一下成员变量改变没有 答案还是没有改变.
}
}
不管是静态成员变量还是非静态的,都是一样的结果.
结果告诉我们当一个方法的参数名与类的成员变量名相同时,方法里面调用那个成员变量的所有操作都会当成是对传入的参数变量的操作.除非你载成员变量前面加上this这个关键字才行,这里就体现了this关键的的重大作用了.
void change(){ ...//no argument, a is the class field