日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

this关键字详解

發布時間:2025/3/14 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 this关键字详解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

  在java中,編譯器會為每個對象分配一個this關鍵字。在代碼中使用關鍵字可以使代碼更優雅。下面我就列舉一下this關鍵字常見的幾種場景。

1、this代表當前對象調用成員變量和方法,也是用的最多的地方。

1 package demo; 2 /** 3 * 測試this代表當前對象調用成員變量和方法 4 * @author dyf 5 * 6 */ 7 public class TestThis { 8 private String name; 9 private int age; 10 11 void eat(){ 12 System.out.println("劉二狗正在吃飯!"); 13 } 14 15 void print(String name,int age){ 16 this.name = name; //區分成員變量和參數 17 this.age = age; 18 this.eat(); //this代表當前對象 19 System.out.println(name + "今年" + age); 20 } 21 22 public static void main(String[] args) { 23 //初始化對象的時候就會調用無參構造器 24 TestThis tt = new TestThis(); 25 tt.print("劉二狗",18); 26 } 27 }

打印結果:

?

2、代表當前對象的句柄,如果你希望將句柄返回給當前對象,就可以在return中使用。也就是說當你使用某個對象執行一個方法,需要在方法內執行邏輯代碼,但是最后又希望拿到該對象的句柄并對同一對象執行多項操作。

1 package demo; 2 /** 3 * 測試this代表當前句柄并返回給當前對象 4 * @author dyf 5 * 6 */ 7 public class TestThis { 8 private int i = 0; 9 //返回當前對象的方法 10 TestThis test(){ 11 //執行這個方法,我們可以在里面做大量的操作之后再把句柄返回給當前對象 12 i++; 13 return this; 14 } 15 //打印的方法 16 void print(){ 17 System.out.println("i = " + i); 18 } 19 20 public static void main(String[] args) { 21 TestThis tt = new TestThis(); 22 tt.test().test().test().print(); 23 } 24 }

打印結果:

?

3、若同一個類中寫了多個構造器,我們可能需要在一個構造器里調用另一個構造器。為了避免寫重復的代碼使程序更優雅,我們使用this可以做到。this不能調用兩個構造器

代碼如下:

1 package demo; 2 /** 3 * 測試this在構造器里面調用其他構造器 4 * @author dyf 5 * 6 */ 7 public class TestThis { 8 private int count = 0; 9 private String str = new String("null"); 10 11 TestThis(int num){ 12 count = num; 13 System.out.println("帶有整形參數的構造器"+count); 14 } 15 16 TestThis(String s){ 17 System.out.println("帶有字符串參數的構造器"+s); 18 } 19 20 TestThis(String str,int number){ 21 this(number); //調用帶有整形參數的構造器 22 //this(ss); //不能在一個構造器里面同時調用兩個構造器 23 //為了避免成員變量str和參數str混淆,使用this可以避免 24 this.str = str; 25 this.count = number; 26 System.out.println("String && int args"); 27 } 28 29 TestThis(){ 30 this("hello",18);//調用帶有兩個參數的構造器 31 System.out.println("無參構造器"); 32 } 33 34 void print(){ 35 System.out.println("count = " + count + " --- " + "str = " + str); 36 } 37 38 public static void main(String[] args) { 39 //初始化對象的時候就會調用無參構造器 40 TestThis tt = new TestThis(); 41 tt.print(); 42 } 43 }

打印結構:

?

轉載于:https://www.cnblogs.com/dyfbk/p/6873679.html

總結

以上是生活随笔為你收集整理的this关键字详解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。