Java提供了一个this关键字,this关键字总是指向调用该方法的对象,根据this出现位置的不同,this作为对象的默认引用有两种情形:1、构造器中引用该构造器正在初始化的对象。2、在该方法引用调用该方法的对象
this关键字最大的作用就是让类中的一个方法,访问该类里的另一个方法或者实例变量。
public class Dog {
public void jump(){
System.out.println("jump");
}
public void run(){
this.jump();
System.out.println("run");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Dog dog = new Dog();
dog.run();
System.out.println();
dog.jump();
}
}
Java允许对象的一个成员直接调用另一个成员,可以省略this前缀。
static修饰的方法中不能使用this引用,static修饰的方法不能方位不适用static修饰的普通成员,因此静态成员不能直接访问非静态成员。如果确实需要在静态方法中访问另一个普通方法,则只能重新创建一个对象。
大部分时候,普通方法访问另一个普通方法,成员变量时无须使用this前缀,但如果方法里有个局部变量和成员变量同名,但程序又需要在该方法里访问这个被覆盖的成员变量,则必须要使用this前缀。
public class ThisInConstructor {
private static int foo = 4;
public ThisInConstructor(){
int foo = 2;
this.foo = 6;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new ThisInConstructor().foo);
}
}
当this作为对象的默认引用使用时,程序可以像方位普通引用变量一样来访问这个this引用,甚至可以把this当成普通方法的返回值。
public class ReturnThis {
private int age;
public ReturnThis grow(){
age++;
return this;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ReturnThis rt = new ReturnThis();
rt.grow()
.grow()
.grow();
System.out.println(rt.age);
}
}