java中的this關鍵字

來源:互聯網
上載者:User

標籤:this


1.this是什嗎?

this是一個參考型別,在堆中的每一個java對象上都有this,this儲存記憶體位址指向自身。

2.this能用在哪些地方?

第一:this可以用在成員方法中.

第二:this可以用在構造方法中.

文法:this(實參);

通過一個構造方法去調用另一個構造方法。

目的:代碼重用。

this(實參);必須出現在構造方法的第一行

第三:this不能用在靜態方法中。靜態方法的執行不需要java對象的存在,直接使用"類名."的方式去訪問,this代表的是當前對象,所有不用用在靜態方法中。

class MyDate{//Fieldint year;int month;int day;//Constructor//需求:在建立日期對象的時候,預設的日期是:1970-1-1MyDate(){this(1970,1,1);/*this.year = 1970;this.month = 1;this.day = 1;*/}MyDate(int _year,int _month,int _day){year = _year;month = _month;day = _day;}
/*this能用在成員方法中。this就是當前對象.*/public class ThisTest02{public static void main(String[] args){//建立對象Employee e = new Employee(7369,"SMITH");//工作e.work();//建立對象Employee e1 = new Employee(7370,"FORD");//工作e1.work();e.m1();}}class Employee{//員工編號int empno;//員工名String ename;//ConstructorEmployee(){}Employee(int _empno,String _ename){empno = _empno;ename = _ename;}//提供一個員工工作的方法.//this用在成員方法中,誰去調用這個成員方法,this就代表誰。//this指的就是當前對象。public void work(){System.out.println(this.ename + "在工作");//System.out.println(ename + "在工作"); //this. 可以省略}//成員方法public void m1(){this.m2();m2();}//成員方法public void m2(){System.out.println("TESTING");}}

注意:this不能用在靜態方法中。

/*this不能用在靜態方法中.靜態方法的執行根本不需要java對象的存在。直接使用“類名.”的方式訪問。而this代表的是當前對象。所以靜態方法中根本沒有this*/public class ThisTest04{String str;//入口public static void main(String[] args){Person.m1();//str是一個成員變數,必須由  引用.   訪問//System.out.println(str);ThisTest04 tt = new ThisTest04();System.out.println(tt.str); //null}}class Person{//FieldString name;//ConstructorPerson(){}Person(String name){this.name = name;}//靜態方法public static void m1(){//System.out.println(this.name);//如果要想訪問name只能:Person p1 = new Person("劉德華");System.out.println(p1.name);}}


本文出自 “gaogaozi” 部落格,請務必保留此出處http://hangtiangazi.blog.51cto.com/8584103/1661111

java中的this關鍵字

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.