關於構造函數中的this()和super()


今天看到一個這段代碼

public DataSourcePool(String driver, String url, String user, String pwd) throws Exception {
        this(driver, url, user, pwd, 5);
    }

public DataSourcePool(String driver, String url, String user, String pwd, int poolSize) throws SQLException, ClassNotFoundException {
        this.url = url;
        this.user = user;
        this.pwd = pwd;
        this.poolSize = poolSize;
        Class.forName(driver);
        init(3);
    }

  然后突然發現自己忘了構造函數中的this()是干什么用的,雖然憑借原理能夠大致推敲出是調用了另外的構造函數,但具體是怎么樣的還是手動試了下。

public class Person {

    private String name;
    private Integer age;
    private String sex;

    public Person(String name) {
        this.name = name;
    }
    
    public Person(String name, Integer age, String sex) {
        this(name, age);
    }
    
    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
        System.out.println("aa");
    }


    public static void main(String[] args) {
        Person person = new Person("小明", 17, "男");
        System.out.println(person);
        System.out.println(person.name);
        System.out.println(person.age);
        System.out.println(person.sex);
    }

  main方法中的new Person("小明", 17, "男")按理來說是創建了一個信息為(姓名:“小明”,年齡:17歲,性別“男”)的對象,但輸出性別的時候卻是null,最后的輸出結果是

aa
test.Person@1b6d3586
小明
17
null

 而且如下寫法是會報錯的——Recursive constructor invocation——“遞歸構造函數調用”的意思,這樣進入了死循環

public Person(String name, Integer age, String sex) {
        this(name, age, sex);
    }

  由此可知,在一個構造方法中寫this(參數...)方法其實是在調用原本的構造方法時進入this(參數...)這個方法,使用了相對應this(參數...)的構造函數創建了對象。

  super()就是調用父類的構造方法了

 


免責聲明!

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



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