super关键字
super关键字代指父类。在子类的方法中,可以通过 super.属性
/ super.方法
的方式,显示地去调用父类提供的属性/方法。通常情况下, super.
可以省略不写。
public class Student extends Person{
public void a(){
System.out.println(/*super.*/age);
/*super.*/eat();
}
}
在特殊情况下,当子类和父类的属性、方法重名时,想要使用父类的属性/方法,就必须加上修饰符 super
,通过 super.属性
/ super.方法
来调用。
public class Student extends Person{
int age = 20;
public void eat(){
System.out.println("吃小龙虾");
}
public void a(){
System.out.println(super.age);
super.eat();
}
}
super修饰构造器
所有构造器的第一行默认情况下都有 super()
:
public class Student extends Person{
double score;
public Student(){
/*super();*/
}
}
但是一旦你的构造器中显示地使用 super
调用了父类构造器,那么这个 super()
就不会给你默认分配了:
public Student(int age, String name, double score){
super(age,name);
this.score = score;
}
需要注意的是:在构造器中,super
调用父类构造器和 this
调用子类构造器只能存在一个,两者不能共存。因为 super
修饰构造器要放在第一行,this
修饰构造器也要放在第一行,二者选其一即可。(要不然先 super
再 this
调用的 this
构造器中,又调用了一次 super
空构造器,因为所有构造器的第一行默认情况下都有 super()
)
继承条件下构造方法的执行过程
继承条件下构造方法的执行过程将通过下面一个例子进行讲解:
public class Person {
int age;
String name;
public Person(int age, String name) {
super();
this.age = age;
this.name = name;
}
public Person() {
}
}
public class Student extends Person {
double height ;
public Student() {}
public Student(int age, String name, double height) {
super(age, name);
this.height = height;
}
}
public class Test {
public static void main(String[] args) {
Student s = new Student(20,"huan",180);
}
}
在上述代码中,首先执行 main()
方法,调用 Student
类的有参构造,在它的有参构造中第一句是调用父类 Person
类的有参构造器,而在 Person
类的有参构造中第一句是用 super
调用父类 Obeject
类的构造器,对 Object
类进行一些初始化操作。