------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
this关键字总是指向调用该方法的对象。
this可以代表任何对象,当this出现在某个方法体中时,它所代表的对象是不确定的,但它的类型是确定的,它所代表的对象只能是当前类的(在那个类中就是那个类),只有当这
个方法被调用时,它所代表的对象才被确定下来。谁在调用这个方法,this就代表谁。
〉在构造器中引用该构造器正在初始化的数据
〉在方法中引用调用该方法的对象
this关键字最大的作用就是让类中的一个方法,访问该类中另一个方法或实例变量。
public class Dog
{
public void jump(){
system.out.println("正在执行jump()方法");
}
public void run(){
//this 引用调用run()方法中的对象
//this代表run()对象
this.jump();
}
}
public class Text
{
//定义一个foo成员变量
public int foo;
public ThisInCotructor()
{
//在构造器中定义一个foo局部变量
int foo =0;
//使用this 代表该构造器正在初始化的对象
//下面的代码会将该构造器正在初始化的对象的foo成员变量设为6
this.foo =6;
}
public static void main(String[] args)
{
//输出6
System.out.println(new ThisInContructor().foo)
}
}
如果方法中有个局部变量和成员变量同名,而程序又需要访问这个被覆盖的成员变量,则必须使用this。
public class Test
{
private String name ="李刚";
private static double price =78.0;
public static void main(Stingp[] args)
{
int price =65;
//输出65,局部变量覆盖了成员变量
System.out.println(price);
//输出78.0
System.out.println(Test.price);
//运行info()方法
new Test.info();
}
public void info()
{
String name ="小明";
//System.out.println(name);
//使用this来作为name变量的限定
//输出,李刚
System.out.println(this.name);
}
}