App下載

Java this 關(guān)鍵字詳解

猿友 2021-01-04 14:51:25 瀏覽數(shù) (2388)
反饋

this 關(guān)鍵字

this 關(guān)鍵字代表了所屬函數(shù)的調(diào)用者對(duì)象。

this 關(guān)鍵字的作用:

  • 如果存在同名成員變量與局部變量時(shí),在方法內(nèi)部默認(rèn)是訪問局部變量的數(shù)據(jù),可以通過 this 關(guān)鍵字指定訪問成員變量的數(shù)據(jù);
  • 在一個(gè)構(gòu)造函數(shù)中可以調(diào)用另外一個(gè)構(gòu)造函數(shù)初始化對(duì)象。

this 關(guān)鍵字調(diào)用其他的構(gòu)造函數(shù)要注意的事項(xiàng): 

  • this 關(guān)鍵字調(diào)用其他的構(gòu)造函數(shù)時(shí),this關(guān)鍵字必須要位于構(gòu)造函數(shù)中的第一個(gè)語句;
  • this 關(guān)鍵字在構(gòu)造函數(shù)中不能出現(xiàn)互相調(diào)用的情況,因?yàn)槭且粋€(gè)死循環(huán)。

this 關(guān)鍵字要注意的事項(xiàng):

  • 存在同名的成員變量與局部變量時(shí),在方法的內(nèi)部訪問的是局部變量(java采取的是“就近原則”的機(jī)制訪問的);
  • 如果在一個(gè)方法中訪問了一個(gè)變量,該變量值存在成員變量的情況下,那么java編譯器會(huì)在該變量的前面添加this關(guān)鍵字。

this關(guān)鍵字調(diào)用其他的構(gòu)造函數(shù)要注意的事項(xiàng): 

  • this關(guān)鍵字調(diào)用其他的構(gòu)造函數(shù)時(shí),this關(guān)鍵字必須要位于構(gòu)造函數(shù)中的第一個(gè)語句;
  • this關(guān)鍵字在構(gòu)造函數(shù)中不能出現(xiàn)互相調(diào)用的情況,因?yàn)槭且粋€(gè)死循環(huán)。

推薦好課:深入解析Java面向?qū)ο?/a>、Java基礎(chǔ)入門到框架實(shí)踐


this關(guān)鍵字實(shí)例

class Student{

    int id; //身份證

    String name; //名字

    //目前情況: 存在同名的成員變量與局部變量,在方法內(nèi)部是使用局部變量的。

    public Student(int id, String name) { //一個(gè)函數(shù)的形式參數(shù)也是屬于局部變量。

        //調(diào)用了本類的一個(gè)參數(shù)的構(gòu)造方法

        //this(name);//如果能在這里調(diào)用到下面一個(gè)參數(shù)的構(gòu)造方法時(shí),那就可以解決重復(fù)代碼的問題。

        this(); //調(diào)用了本類的無參的構(gòu)造方法。

        this.id = id; //this.id = id; 局部變量的id給成員變量的id賦值。

        System.out.println("兩個(gè)參數(shù)的構(gòu)造方法調(diào)用了...");

    }

    public Student() {

        System.out.println("無參的構(gòu)造方法被調(diào)用了...");

    }

    public Student(String name) {

        this.name = name;

        //System.out.println("一個(gè)參數(shù)的構(gòu)造方法被調(diào)用了...");

    }

}

public class Demo1 {

    public static void main(String[] args) {

        Student s = new Student(110, "迪迦");

        System.out.println("編號(hào): "+s.id+"  名字: "+s.name);

        Student s2 = new Student("W3CSCHOOL");

        System.out.println("名字: "+s2.name);

    }

}


0 人點(diǎn)贊