Java的知识点9——this关键字
this關(guān)鍵字
構(gòu)造方法是創(chuàng)建Java對象的重要途徑,通過new關(guān)鍵字調(diào)用構(gòu)造器時,構(gòu)造器也確實返回該類的對象,但這個對象并不是完全由構(gòu)造器負責創(chuàng)建。
創(chuàng)建一個對象分為如下四步:
1. 分配對象空間,并將對象成員變量初始化為0或空
2. 執(zhí)行屬性值的顯式初始化
3. 執(zhí)行構(gòu)造方法
4. 返回對象的地址給相關(guān)的變量
this的本質(zhì)就是“創(chuàng)建好的對象的地址”! 由于在構(gòu)造方法調(diào)用前,對象已經(jīng)創(chuàng)建。因此,在構(gòu)造方法中也可以使用this代表“當前對象”
this最常的用法:
? ? ? ? 1. 構(gòu)造方法中,this總是指向正要初始化的對象
? ? ? ? ? ? ? ? ? ?2. 使用this關(guān)鍵字調(diào)用重載的構(gòu)造方法,避免相同的初始化代碼。但只能在構(gòu)造方法中用,并且必須位于構(gòu)造方法的第一句。
? ? ? ? ? ? 3. this不能用于static方法中。
this代表“當前對象”示例
public class Test5 {int id;String name;String pwd;public Test5() {}public Test5(int id,String name) {System.out.println("正在初始化已經(jīng)創(chuàng)建好的對象:"+this);this.id=id;this.name=name;}public void login() {System.out.println(this.name+",要登錄");}public static void main(String[] args) {Test5 u3=new Test5(101,"代止兮");System.out.println("打印代止兮對象:"+u3);u3.login();}}this()調(diào)用重載構(gòu)造方法
public class TestThis {int a,b,c;TestThis(){}TestThis(int a,int b){this();//調(diào)用無參的構(gòu)造方法,并且必須位于第一行a=a; //這里都是指的局部變量而不是成員變量this.a=a; //用this來區(qū)分局部變量和成員變量this.b=b; }TestThis(int a,int b,int c){this(a,b); //調(diào)用帶參的構(gòu)造方法,并且必須位于第一行this.c=c;}void sing() {}void eat() {this.sing(); //調(diào)用本類的sing()System.out.println("你媽媽喊你回家吃飯!");}public static void main(String [] args) {TestThis hi=new TestThis(2,3);hi.eat();} }構(gòu)造方法的重載
構(gòu)造方法重載(創(chuàng)建不同用戶對象)
如果方法構(gòu)造中形參名與屬性名相同時,需要使用this關(guān)鍵字區(qū)分屬性與形參。
public class User {int id;String name;String pwd;public User() {}public User(int id,String name) {super();this.id=id;this.name=name;}public User(int id,String name,String pwd) {this.id=id;this.name=name;this.pwd=pwd;}public static void main(String[] args) {User u1=new User();User u2=new User(101,"止小兮");User u3=new User(100,"代止兮","123456");} }總結(jié)
以上是生活随笔為你收集整理的Java的知识点9——this关键字的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java知识点8——垃圾回收原理和算法、
- 下一篇: Java的知识点10——static关键