首页 > 其他 > 详细

关于构造函数中的this()和super()

时间:2019-09-06 12:46:59      阅读:80      评论:0      收藏:0      [点我收藏+]

今天看到一个这段代码

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

 

关于构造函数中的this()和super()

原文:https://www.cnblogs.com/woyujiezhen/p/11474059.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!