Java中this 關鍵字的用法
阿新 • • 發佈:2021-02-03
技術標籤:Java_basic
1、代指類中的屬性,我們採用this 程式碼如下:
/** * 1、類中的屬性呼叫都要用this */ public class TestStudent001 { public static void main(String[] args) { Student001 st001 = new Student001("Kobe",38); System.out.println(st001.getInfo()); } } class Student001{ private String name; private Integer age; // public Student001(String ss,Integer mm){ // name = ss; // age = mm; // } public Student001(String name,Integer age){ this.name = name; this.age = age; } public String getInfo(){ return "學生名: "+name+" 的年紀"+age; } } // 方法中的引數名稱不好,所以我們就用this 明確,引數的作用更加形象化。如上程式碼,代表的是外層的this物件
2、代指當前物件
//this 關鍵字的作用 public class TestStudent { public static void main(String[] args) { Student studentA = new Student(); System.out.println("學生A "+ studentA); studentA.print(); System.out.println("-----------這是分界線--------------"); Student studentB = new Student(); System.out.println("學生B "+ studentB); studentB.print(); } } /** * 所謂的當前物件指的就是當前正在呼叫類中方法的物件 * 哪個物件呼叫了print方法,this 就自動與此物件指向同一塊記憶體地址。this就是當前呼叫方法的物件 */ class Student{ public void print(){ System.out.println("this------- " + this); } }
輸出結果:
學生A [email protected]
this------- [email protected]
-----------這是分界線--------------
學生B [email protected]
this------- [email protected]
3、解決方法的重複呼叫
//利用this 解決方法的重複呼叫 this()呼叫構造方法形式的程式碼只能放在構造方法的首行;進行構造方法互相呼叫的時候,一定要預留呼叫的出口 public class TestStudent002 { public static void main(String[] args) { Student002 stu002 = new Student002("James",36); System.out.println(stu002.getInfo()); } } class Student002{ private String name; private Integer age; public Student002(){ System.out.println("這是一個類的無參構造"); } public Student002(String name){ this();//呼叫本類的無參構造 System.out.println("這裡有一個引數"); this.name = name; } public Student002(String name,Integer age){ this(name); System.out.println("這裡有二個引數"); this.age = age; } public String getInfo(){ return "學生名: "+name+" 的年紀"+age; } }
輸出結果:
這是一個類的無參構造
這裡有一個引數
這裡有二個引數
學生名: James 的年紀36