无参构造器
2020-12-21 本文已影响0人
susu2016
1、子类没有构造函数时,自动调用父类的无参构造函数
public class Animal {
Animal(){
System.out.println("Animal NoArgsConstructor");
}
Animal(int a){
System.out.println("Animal args construction");
}
}
public class Bird extends Animal {
public static void main(String[] args) {
Animal animal = new Bird();
}
}
运行结果:Animal NoArgsConstructor
2、子类显示指定构造函数时,也会自动调用父类构造方法
public class Bird extends Animal {
Bird() {
System.out.println("Bird NoArgsConstructor");
}
public static void main(String[] args) {
Animal animal = new Bird();
}
}
class Animal {
Animal(){
System.out.println("Animal NoArgsConstructor");
}
Animal(int a){
System.out.println("Animal args construction");
}
}
运行结果:Animal NoArgsConstructor
Bird NoArgsConstructor
3、父类没有无参构造函数时,子类缺省无参构造函数或者指定无参构造函数都会报错
报错情况1:
public class Bird extends Animal {
Bird() {
System.out.println("Bird NoArgsConstructor");
}
public static void main(String[] args) {
Animal animal = new Bird();
}
}
class Animal {
Animal(int a){
System.out.println("Animal args construction");
}
}
报错情况2:
public class Bird extends Animal {
public static void main(String[] args) {
Animal animal = new Bird();
}
}
class Animal {
Animal(int a){
System.out.println("Animal args construction");
}
}