Java 中的this關鍵字

來源:互聯網
上載者:User

標籤:hone   gets   person   scree   oat   ati   mem   建構函式   one   

1.this關鍵字代表當前對象

  this.屬性  操作當前對象的屬性

  this.方法  調用當前對象的方法

2.封裝對象的屬性的時候,經常會使用this關鍵字
public class Telphone {    private float screen;    private float cpu;    private float mem;        public void sendMessage(){        System.out.println("sendMessage");    }        public float getScreen() {        return screen;    }    public void setScreen(float screen) {        this.screen = screen; // 操作當前對象的屬性        this.sendMessage();      // 調用當前對象的方法    }    public float getCpu() {        return cpu;    }    public void setCpu(float cpu) {        this.cpu = cpu;    }    public float getMem() {        return mem;    }    public void setMem(float mem) {        this.mem = mem;    }    public Telphone(){        System.out.println("com.imooc.Telphone");    }    public Telphone(float newScreen,float newCpu,float newMem){        if(newScreen<3.5f){            System.out.println("...............");            screen = 3.5f;        }        cpu = newCpu;        mem = newMem;        System.out.println("----------------");    }}
this

this 是自身的一個對象,代表對象本身,可以理解為:指向對象本身的一個指標

this 的用法在 Java 中大體可以分為3種:

1.普通的直接引用

這種就不用講了,this 相當於是指向當前對象本身。

2.形參與成員名字重名,用 this 來區分:

package s2;class Person {    private int age = 22;    public Person() {        System.out.println("初始化年齡:" + age);    }        public int getAge(int age) {        this.age = age;  // 形參與成員名字重名        return this.age;    }}public class Test03 {    public static void main(String[] args) {        Person Harry = new Person();        System.err.println("Harry‘s age is:" + Harry.getAge(33));    }}

運行結果:

初始化年齡:22Harry‘s age is:33

3.引用建構函式

這個和 super 放在一起講,見下面

 

Java 中的this關鍵字

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.