当函数中传递参数的局部变量与成员变量同名诗,就可以用this来区分成员变量和局部变量,被this修饰的是成员变量
另外楼主可以把构造函数放在main函数之前,这样看起来会比较直观一些。 作者: 史卜坤 时间: 2012-7-4 10:14
this为一系统资源,只允许用户读而不允许写,它存放当前对象的地址(引用)
this变量有以下作用:
1. 构造方法重用:
public class Rectangle
{
public Rectangle(Location at, Shape size)
{…}
public Rectangle(Shape size,Location at)
{
this(at, size);
}
public Rectangle(Location at)
{
this(at, new Shape(100,100));
}
public Rectangle(Shape size)
{
this(size, new Location(1,1));
}
public Rectangle()
{
this(new Location(1,1), new Shape(100,100));
}
}
2、消除歧义:
class Location
{
private int x;
private int y;
public Location(int x,int y)
{
this.x=x;
this.y=y;
}
……
}
3、返回对象-链式方法调用:
public class Count
{
private int i = 0;
Count increment()
{
i++;
return this; //返回对象的地址,所以我们可以链式访问它
}
void print()
{
Sop("i = " + i);
}
}
public class CountTest
{
p s v main(String[] args)
{
Count x = new Count();
x.increment().increment().print();
}
}
4、作为参数传递"this”变量-进行回调:
假设有一个容器类和一个部件类,在容器类的某个方法中要创建部件类的实例对象,而部件类的构造方法要接受一个代表其所在容器的参数。例如:
class Container
{
Component comp;
public void addComponent()
{
comp = new Component(this);
//代表你所创建的对象,因为它要用到.
}
}
class Component
{
Container myContainer;
public Component(Container c)
{
myContainer = c;
}
}
慢慢的就会接触到更多更深入的应用的,加油加油,与楼主更勉之!!!作者: 王海宇 时间: 2012-7-4 16:12
简单一些去想,要知道,在java中,如果一个类的(成员函数内部)所定义的一个变量的变量名与该类的一个成员变量的变量名相同,在方法内部直接使用变量名去访问这个变量时,访问到的将会是方法内部所定义的变量,而不是类的成员变量。再来看你的例子,你的例子中传递给构造函数的参数 s 相当于一个方法的内部变量,若直接用变量名去访问,访问到的将会是这个“内部变量”。若要访问外部的变量 s ,就需要使用this关键字,来表示访问的是这个HeimaThis对象中的变量 s ,而不是构造函数里面的变量 s