1.當成員變量和局部變量重名時,在方法中使用this時,表示的是該方法所在類中的成員變量。(this是當前對象自己)
/**
* Created by lenovo on 2016/3/11.
* 當成員變量和局部變量同名時,可以用關鍵字this進行區分
* this:代表對象 (當前對象)
*? ? ? this就是所在函數所屬對象的引用
*/
class Person
{
private String name;//為成員變量 在堆中存在
private int age;
Person(String name)//name為局部變量 在棧里存在
{
this.name=name;//沒有this的話 進棧后有個局部變量name 此時的name和堆中的沒有關系 只不過將棧里的name賦給了自己
//this.name為成員變量 在堆中存在
}
//構造函數用于對象初始化
public void speak(){
System.out.println(name + ":" + age);
}
}
public class Demo1 {
public static void main(String[] args)
{
Person p=new Person("Lily");
p.speak();
}
}
2.this也可以用于在構造函數中調用其他構造函數
/*只能定義在構造函數的第一行 初始化動作必須首先執行
值得注意的是:
1:在構造調用另一個構造函數,調用動作必須置于最起始的位置。
2:不能在構造函數以外的任何函數內調用構造函數。
3:在一個構造函數內只能調用一個構造函數。
*/
class Person
{
private String name;//為成員變量 在堆中存在
private int age;
Person()
{
//this("haha");//調用Person(String name)方法
name="baby";
age=3;
System.out.println("Person run");
}
Person(String name)//name為局部變量 在棧里存在
{
this();//直接調用Person()方法
this.name=name;
}
//構造函數用于對象初始化
Person(String name,int age)
{
//this.name=name;
this(name);//在這里找到參數值為String的構造函數
this.age=age;
}
public void speak(){
System.out.println(name + ":" + age);
}
}
3把自己當作參數傳遞時,也可以用this.(this作當前參數進行傳遞)
classA {
publicA() {
newB(this).print();//調用B的方法
}
publicvoidprint() {
System.out.println("HelloAA from A!"); ? ? ? ? ? ? ? ? ? ?3 HelloAA from A!
}
}
classB {
Aa;
publicB(A a) {
this.a= a;
}
publicvoidprint() {
a.print();//調用A的方法? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 1 HelloAA from A!? ? 4 HelloAA from A!
System.out.println("HelloAB from B!");? ? ? ? ? ? ? ? ? 2 HelloAB from B!? ? ? 5 HelloAB from B!
}
}
publicclassHelloA {
publicstaticvoidmain(String[] args) {
A aaa =new?A();
aaa.print();
B bbb =new?B(aaa);
bbb.print();
}
}
結果為:
1 HelloAA from A!
2 HelloAB from B!
3 HelloAA from A!//aaa.print();
4 HelloAA from A!
5 HelloAB from B!
在這個例子中,對象A的構造函數中,用new B(this)把對象A自己作為參數傳遞給了對象B的構造函數。
4 有時候,我們會用到一些內部類和匿名類,如事件處理。當在匿名類中用this時,這個this則指的是匿名類或內部類本身。這時如果我們要使用外部類的方法和變量的話,則應該加上外部類的類名。如:
public class HelloB {
int i = 1;
public HelloB() {
Thread thread = new Thread() {
public void run() {
for (int j=0;j<20;j++) {
HelloB.this.run();//調用外部類的方法
try {
sleep(1000);
} catch (InterruptedException ie) {
}
}
}
}; // 注意這里有分號
thread.start();
}
public void run() {
System.out.println("i = " + i);
i++;
}
public static void main(String[] args) throws Exception {
new HelloB();
}
}
在上面這個例子中, thread是一個匿名類對象,在它的定義中,它的run函數里用到了外部類的run函數。這時由于函數同名,直接調用就不行了。這時有兩種辦法,一種就是把外部的run函數換一個名字,但這種辦法對于一個開發到中途的應用來說是不可取的。那么就可以用這個例子中的辦法用外部類的類名加上this引用來說明要調用的是外部類的方法run。
5this同時傳遞多個參數
publicclassTestClass {
intx;
inty;
staticvoidshowtest(TestClass tc) {//實例化對象
System.out.println(tc.x+" "+ tc.y);
}
voidseeit() {
showtest(this);
}
publicstaticvoidmain(String[] args) {
TestClass p =newTestClass();
p.x= 9;
p.y= 10;
p.seeit();
}
}
代碼中的showtest(this),這里的this就是把當前實例化的p傳給了showtest()方法,從而就運行了