Java基礎-this和super的區別,java-thissuper

來源:互聯網
上載者:User

Java基礎-this和super的區別,java-thissuper

package com.cn.This;/** * this與super的區別: * 1.this相當於指向本類的對象的指標,調用本類的另一種類型的構造方法 * 2.super調用的是父類中形參相同的構造方法 * 3.兩者都需要放在構造方法內的第一行 * 4.兩者不能同時出現在一個建構函式中,因為this必然會調用其他的建構函式,進而會產生兩個super * 5.兩者都指對象,所以不能在含有static的環境中使用 * @author P0111220 * */class Person{    public void pro(String msg) {        System.out.println(msg);    }    public Person() {        // TODO Auto-generated constructor stub        pro("父類的無參構造方法!!");    }    public Person(String mString){        pro("父類含一個參數的構造方法:"+mString);    }}class Chinese extends Person{    public Chinese() {        // TODO Auto-generated constructor stub        super();//調用父類的構造方法        pro("調用父類的無參構造方法");    }    public Chinese(String name){        super(name);//形參相同指的是參數類型相同,參數名可以隨便        pro("調用父類相同形參類型的方法:"+name);    }        public Chinese(String name,int age){        this(name);//相當於指向本類中另一種類型的構造方法        pro("age:"+age);    }}public class ThisSuperTest {    public static void main(String[] args) {        Chinese chinese= new Chinese();        chinese = new Chinese("狗子");        chinese = new Chinese("狗子",12);    }}
View Code

關於Java中this和super關鍵字的一些理解,代碼中注釋出都做了標註,也貼出了運行結果,希望對各位有用。

聯繫我們

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