this關鍵字

this關鍵字

this關鍵字代表是對象的引用。也就是this在指向一個對象,所指向的對象就是調用該函數的對象引用。(好繞!!!)

那麼:this到底是什麼?
this代表所在函數所屬對象的引用。

實際工作中,存在着構造函數之間的相互調用,但是構造函數不是普通的成員函數,不能通過函數名自己接調用所以sun公司提供this關鍵字。

class Student {
    String name;
    String gender;
    int age;

    Student() {
    }

    Student(String name) {
        this();
        this.name = name;
    }

    Student(String name, String gender, int age) {
        this(name);
        this.gender = gender;
        this.age = age;
    }

    void speak() {
        run();
        System.out.println("姓名:" + name + " 性別:" + gender + " 年齡:" + age
                + " 哈哈!!!");
    }

    void run() {
        System.out.println("run.....");
    }

}

class Demo2 {

    public static void main(String[] args) {
        Student p = new Student("jack", "男", 20);
        Student p2 = new Student("rose", "女", 18);

        p.speak();
        p2.speak();
    }
}

注:
1.this只能在非靜態中(沒有static修飾的)函數使用
2.構造函數間相互調用必須放在構造函數的第一個語句中,否則編譯錯誤
3.可以解決構造函數中對象屬性和函數形參的同名問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章