this 关键字出现在类的构造方法中时,代表使用该构造方法所创建的对象。
public class People {
/**
* @author 牧羊的伯格女皇
* @param args
* date:2015-10-14
*/
private int age;
private String name;
People(String name){
this.name = name;
this.printInfo(); //也可省略this
}
public void printInfo(){
age = 21; //这里也可以使用 this.age
System.out.println( name + "的年龄为: " + age );
}
public static void main(String[] args) {
People p = new People("牧羊的伯格女皇"); //构造方法中的this就是对象 p
}
}
3. 在实例方法中使用this,实例方法只能通过对象来调用,不能用类名来调用。当this出现在实例方法中时,this就代表正在调用该方法的当前对象。
另外还需要注意的是:当实例成员变量的名字和局部变量的名字相同时,成员变量前面的 "this." 或 "类名."就不可省略。
public class Demo {
public int x = 100;
public static int y;
public void A(){
int x =10;
Demo.y = 20;
//当实例成员变量与局部变量的名字相同时候,不能省略this关键字
System.out.println("x = " +x + "\t this.x = " + this.x);
this.B(); // 当前对象调用了B 也可以说 对象d调用了方法A后,又调用了方法B 此时也可以省略this关键字
C();
}
public void B(){
System.out.println("Hello , B Method !" );
}
public static void C(){
System.out.println("Hello , C Method !");
}
public static void main(String[] args) {
Demo d = new Demo();
d.A();
}
}
注: this关键字不能出现在类方法中,这是因为,类方法可以通过类名直接调用,这时,可能还没有任何对象被创建诞生。
-------更深入理解this关键字: java中this关键字的几种用法