主程序代码如下
class Foo
{
private int x;
public Foo(int x){this.x=x; }
public void.setX(int x){ this.x=x; }
public int getX(){ return x; }
}
public class T{
static Foo fooBar(Foo foo){
foo.setX(100);
return foo; }
public static void main(String []args){
Foo foo=new Foo(300);
System.out.print(foo.getX()+"-");
Foo fooFoo= fooBar(foo);
System.out.print(foo.getX()+"-");
System.out.print(fooFoo.get()+"-");
foo=fooBar(fooFoo);
System.out.print(foo.getX()+"-");
System.out.print(fooFoo.getX());
}}
输出结果是“300-100-100-100”,这个我能理解,但为什么将this.x=x换成x=x,就会变成“0-100-100-100”
将X=X不只是一个初始化X的初值么?怎么不能在第一次输出时付值300呢? 希望各位前辈赐教。谢谢!
class Foo
{
private int x;
public Foo(int x){this.x=x; }
public void.setX(int x){ this.x=x; }
public int getX(){ return x; }
}
public class T{
static Foo fooBar(Foo foo){
foo.setX(100);
return foo; }
public static void main(String []args){
Foo foo=new Foo(300);
System.out.print(foo.getX()+"-");
Foo fooFoo= fooBar(foo);
System.out.print(foo.getX()+"-");
System.out.print(fooFoo.get()+"-");
foo=fooBar(fooFoo);
System.out.print(foo.getX()+"-");
System.out.print(fooFoo.getX());
}}
输出结果是“300-100-100-100”,这个我能理解,但为什么将this.x=x换成x=x,就会变成“0-100-100-100”
将X=X不只是一个初始化X的初值么?怎么不能在第一次输出时付值300呢? 希望各位前辈赐教。谢谢!
public Foo(int x){this.x=x; }改成
public Foo(int y){x=y; }输出结果是“300-100-100-100”
是指当前对象的x属性等于参数xx = x
还是参数,只是临时变量
嗯,就是这样。x = x 是本地方法的局部变量覆盖了类的全局属性
this.x 是指类的全局属性