在Java中,this關(guān)鍵字表示當(dāng)前對象的引用。它可以用來引用當(dāng)前對象的實例變量,方法或構(gòu)造函數(shù)。this關(guān)鍵字常用于以下幾種情況:
public class Person {
private String name;
private int age;
public Person() {
this("John", 30);
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Person {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
public class OuterClass {
private int x = 10;
public void createInnerClass() {
InnerClass inner = new InnerClass() {
public void printOuterX() {
System.out.println(OuterClass.this.x);
}
};
inner.printOuterX();
}
private class InnerClass {
}
}
總之,this關(guān)鍵字可以用來引用當(dāng)前對象的實例變量,方法或構(gòu)造函數(shù),以及區(qū)分局部變量和實例變量。