Java 中的 super 关键字

1. 使用 super 可以从子类中调用父类的构造方法、普通方法、访问父类属性。与 this 调用构造方法的要求一样,语句必须放在子类的构造方法的首行

2. 访问属性、调用普通方法、调用构造方法 this 与 super 的区别
(1) 访问属性:this 访问本类中的属性,如果本类中没有此属性,则从父类中继续查找。super 是访问父类中的属性。
(2) 调用方法:this 访问本类中的方法,如果本类中没有此方法,则从父类中继续查找。super 是访问父类中的方法。
(3) 调用构造:this 调用本类的构造函数,必须放在构造方法的首行。super 是调用父类的构造函数,必须放在子类构造方法的首行。

3. super 和 this 关键字是不能同时在构造方法中出现的,因为两者在调用构造方法时都必须要放在首行,所以会冲突。需要注意的是,无论子类怎样操作,最终都是要先调用父类的构造方法。

4. 例子

class Person {
    public String name;
    public int age;

    public Person(String name, int age) {
        this(name); //ok and must be first
        //Person(name); //error: cannot find symbol
        //this.Person(name); //error: cannot find symbol
        this.age = age;
    }
    public Person(String name) {
        this.name = name;
    }
    public Person() { //若是提供了构造方法,默认的就没有了,需要提供一个
        this.name = "undefined";
        this.age = -1;
    }

    public void printInfo() {
        System.out.println("name = " + name + " age = " + age);
    }
}

class Student extends Person {
    String school;

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

    public void printInfo() {
        System.out.println("name = " + name + " age = " + age + " school = " + school);
    }
}

public class SuperTest {
    public static void main(String args[]) {
        Person p = new Person("XiaoLi", 27);
        p.printInfo();
        ////error: incompatible types, required:Student, found:void. 在 new Student 位置加括号也不行!
        //Student t = new Student("DaLiang", 28, "University").printInfo();
        Student t = new Student("DaLiang", 28, "University");
        t.printInfo();
    }
}

# java SuperTest
name = XiaoLi age = 27
name = DaLiang age = 28 school = University
原文地址:https://www.cnblogs.com/hellokitty2/p/15491794.html