您的位置 首页 java

Java面试基础回顾09-this和super的使用总结

this代表当前对象的引用

super代表父类对象的引用

使用范围:

this.子类成员变量 this.子类成员方法 this(…):可以根据参数匹配调用当前类的构造器

super.父类成员变量 super.父类成员方法 super(…):可以根据参数匹配访问父类的构造器

注意:this(..)和super(…)必须放在构造器的第一行,否则会报错。所以this(…)和super(…)不能同时出现

 class Student{

    private String name;
    private Integer age;
    private String schoolName;

    public Student() {
    }

    public Student(String name,Integer age){
        //this(...)和super(...)不能同时出现
        //super();
        this(name,age,"黑马");
    }

    public Student(String name, Integer age, String schoolName) {
        super();
        this.name = name;
        this.age = age;
        this.schoolName = schoolName;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public String getSchoolName() {
        return schoolName;
    }

    public void setSchoolName(String schoolName) {
        this.schoolName = schoolName;
    }
}  

文章来源:智云一二三科技

文章标题:Java面试基础回顾09-this和super的使用总结

文章地址:https://www.zhihuclub.com/190252.shtml

关于作者: 智云科技

热门文章

网站地图