空构造器中都存在一个隐藏的super(),用于调用父类的空构造器。
public class Student extends Person{
double store;
public Student(){
super();//可以不写
}
}
public class Person {
int age;
String name;
public Person(){
super();
}
}
Person空构造器调的是Object。
super调用父类带参数的构造器
//父类代码
public class Person {
int age;
String name;
public Person(){
super();
}
public Person(int age,String name){
this.age = age;
this.name = name;
}
}
//子类
public class Student extends Person{
double store;
public Student(){
super();//可以不写
}
public Student(double store){
this.store = store;
}
public Student(double store,int age,String name){
this.store = store;
super(age, name);
}
}
Student类中的带参数构造器调用Person类中的带参构造器super(age,name);
上面的代码有个错误!
super(age,name)要放在方法的第一行。跟this调用构造器类似。
正确代码如下:
public Student(double store,int age,String name){
super(age, name);
this.store = store;
}
构造器中如果使用了super调用父类构造器后,不分配super()
在构造器中, super调用父类构造器和this调用子类构造器只能存在其中一个,不能共存。