关于构造函数中的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()就是调用父类的构造方法了

 

posted on 2019-09-06 12:11  我欲皆真  阅读(772)  评论(0编辑  收藏  举报

导航