《Java基礎知識》Java this關鍵字詳解


this 關鍵字用來表示當前對象本身,或當前類的一個實例,通過this可以調用對象的所有方法和屬性。

例如:

public class Demo {
    private int x = 10;
    private int y = 15;

    public void sum(){
        //通過this獲取成員變量,this可以省略。
        int z = this.x + this.y;   
        System.out.println("x+y = "+z);
    }

    public static void main(String[] args) {
        Demo demo = new Demo();
        demo.sum();
    }
}

運行結果:

使用this區分同名變量

public class Demo {
    private String name;
    private int age;

    public Demo(String name,int age){
        //this不能省略,this.name 指的是成員變量, 等於后面的name 是傳入參數的變量,this可以很好的區分兩個變量名一樣的情況。
        this.name = name;
        this.age = age;
    }
    public static void main(String[] args){
        Demo demo = new Demo("微學院",3);
        System.out.println(demo.name + "的年齡是" + demo.age);
    }
}

運行結果:

this作為方法名來初始化對象

public class Demo {
    private String name;
    private int age;

    public Demo(){
        /**
         * 構造方法中調用另一個構造方法,調用動作必須置於最起始位置。
         * 不能在構造方法之外調用構造方法。
         * 一個構造方法只能調用一個構造方法。
         */
        this("微學院",3);
    }

    public Demo(String name,int age){
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args){
        Demo demo = new Demo();
        System.out.println(demo.name + "的年齡是" + demo.age);
    }
}

運行結果:

 this作為參數傳遞

class Person{    
    public void eat(Apple apple){
        Apple peeled = apple.getPeeled();
        System.out.println("Yummy");
    }
}
class Peeler{
    static Apple peel(Apple apple){
        return apple;
    }
}
class Apple{
    Apple getPeeled(){
        //傳入this,就是傳入Apple。
        return Peeler.peel(this);
    }
}
public class This{
    public static void main(String args[]){
        new Person().eat(new Apple());
    }
}

this 用法就到這里。

參考:https://www.cnblogs.com/yefengyu/p/4821582.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM