- 创建类时指定了有参数构造函数后,系统默认不会创建无参数构造函数,需要自己手动创建。
- 创建子类的对象实例时,默认会先调用父类的无参数的构造函数(默认构造函数)。
- 若父类未定义无参数构造函数,则在编译阶段报错。
- 若子类指定了父类的有参构造函数,则可以通过编译和运行。
子类声明super(id, city)显示调用父类有参构造函数
class Predessor {
private int id;
private String city;
public Predessor(int id, String city) {
this.id = id;
this.city = city;
}
@Override
public String toString() {
return "Predessor [id=" + id + ", city=" + city + "]";
}
}
class Successor extends Predessor {
private String name;
private String sex;
public Successor(String name, String sex, int id, String city) {
super(id, city);
this.name = name;
this.sex = sex;
}
@Override
public String toString() {
return "Successor [name=" + name + ", sex=" + sex + "]";
}
}
public class CallConstructorTest {
public static void main(String[] args) {
Successor s2 = new Successor("A", "male", 1, "HZ");
System.out.println(s2);
}
}
输出
Successor [name=A, sex=male]
父类未定义无参数构造函数,子类不声明super(id, city)
public Successor(String name, String sex) {
this.name = name;
this.sex = sex;
}
编译报错
Implicit super constructor Predessor() is undefined. Must explicitly invoke another constructor
父类显示定义无参数构造函数,方法调用的传递性
class Predessor {
private int id;
private String city;
public Predessor() {
System.out.println("调用了 Predessor 无参的构造函数");
}
public Predessor(int id, String city) {
this.id = id;
this.city = city;
}
@Override
public String toString() {
return "Predessor [id=" + id + ", city=" + city + "]";
}
}
class Successor extends Predessor {
private String name;
private String sex;
public Successor() {
System.out.println("调用了 Successor 无参的构造函数");
}
public Successor(String name, String sex) {
this.name = name;
this.sex = sex;
}
@Override
public String toString() {
return "Successor [name=" + name + ", sex=" + sex + "]";
}
}
public class CallConstructorTest {
public static void main(String[] args) {
Successor s = new Successor();
System.out.println(s);
System.out.println("--------------");
Successor s2 = new Successor("A", "male");
System.out.println(s2);
}
}
输出
调用了 Predessor 无参的构造函数
调用了 Successor 无参的构造函数
Successor [name=null, sex=null]
--------------
调用了 Predessor 无参的构造函数
Successor [name=A, sex=male]