JAVA的this和super

來源:互聯網
上載者:User

      當一個對象建立後,Java虛擬機器(JVM)就會給這個對象分配一個引用自身的指標,這個指標的名字就是this。並且this只和特定的對象關聯,而不和類關聯,同一個類的不同對象有不同的this。用法:

(1)this(參數):調用本類中另一種形式的建構函式

class Point {       private int x,y;       public Point(int x,int y)      {            this.x=x; //this它代表當前對象名            this.y=y;      }       public Point()      {           this(0,0);        } } 

(2)如果函數的形參與類中的成員變數同名,這時需用this來指明成員變數名,該功能在(1)中也體現

class Point {       private int x,y;       public Point(int x,int y)      {            this.x=x; //this它代表當前對象名            this.y=y;      } } 

(3)如果函數的局部變數與成員變數相同時,成員變數會被隱藏。此時如果要用到成員變數的話,就需this。

class Point {       private int x = 3;       public Point()      {            int x;           x = 5;           system.out.println(x);          //輸出5           system.out.println(this.x);   //輸出3     } } 

====================================================================================================================

       super的各種用法

(1)使用特殊變數super提供對父類的訪問,可以使用super訪問父類被子類隱藏的變數或覆蓋的方法 

class Animal {        int height,weight;        void Animal()    {   System.out.println("Animal construct!");}       void eat()       {   System.out.println("Animal eat!");  }        void sleep() { System.out.println("Animal sleep!"); }        void breathe()   {   System.out.println("Animal breathe!");  } } class Fish extends Animal {         Fish(){             System.out.println("Fish construct");        }        void breathe(){  //override method breathe()        super.breathe();//在子類中用super訪問被覆蓋的父類函數          System.out.println("Fish bubble");        } } public class TestNew {public static void main(String[] args) {// TODO Auto-generated method stubFish fn=new Fish(); fn.breathe();}}

        編譯運行結果:

Fish construct
Animal breathe!
Fish bubble

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.