this()、super()使用总结

this和super详情
●this: 代表本类对象的引用; super:代表父类存储空间的标识。
在这里插入图片描述
实际上,在以上的总结中,唯独只有this调用本类其他构造器我们是没有接触过的。
曾经我们使用过super()、super.variability
使用过this.variability
但未曾使用过this()来调用本地构造器

至于this指向构造器有什么用,请看如下示例:

package com.demo.thisconst;

public class Main {
    public static void main(String[] args) {
        System.out.println("---------------");
        Student s=new Student("兰华");
        System.out.println(s.getName()+"  "+s.getAge()+"岁,"+s.getSchool());
    }
}

package com.demo.thisconst;

public class Student {
    private String name;
    private int age;
    private String school;

    public Student(String name, int age, String school) {
        this.name = name;
        this.age = age;
        this.school = school;
    }

    public Student(String name) {
        this(name,18,"西顿学院");
    }

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }
}

	运行结果:
	---------------
	兰华  18岁,西顿学院

您可以发现我们在main方法中并未向Student对象传递age、学校这两个参数,但是我们利用this()指向了Student类里面的三元构造器并且向其传递了参数,到这里您也许已经明白this()在工具类里的作用了:一定的初始化+赋予默认值的作用。

作用也许算不上大,重在理解。我们重点要看下面这个知识点:

thi.(…)和super…)使用注意点:

●子类通过 this (…)去调用本类的其他构造器,本类其他构造器会通过super去手动调用父类的构造器,最终还是会调用父类构造器的。
注意: this(… super(…)都只能放在构造器的第- -行, 所以二者不能共存在同- -个构造器中。
其实在一个构造器中默认就有super()方法,只是隐式,当我们在构造器中手动写入this()方法时就会把super()方法给覆盖掉,super就会失效且不允许再写入一个super()方法。
●上面我们提到super的失效问题,第一点又提到最终肯定是会调用super(),只不过在这个时候,就变成通过其他构造器实现的间接调用了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值