南皮县做网站,学校网站建设意义有哪些方面,贵阳餐饮设计公司官网,网站是否开启gzip子类不可以继承父类的构造方法#xff0c;只可以调用父类的构造方法。
子类中所有的构造函数都会默认访问父类中的空参数构造函数#xff0c;这是因为子类的构造函数内第一行都有默认的super#xff08;#xff09;语句。
super#xff08;#xff09;表示子类在初始化…子类不可以继承父类的构造方法只可以调用父类的构造方法。
子类中所有的构造函数都会默认访问父类中的空参数构造函数这是因为子类的构造函数内第一行都有默认的super语句。
super表示子类在初始化时调用父类的空参数的构造函数来完成初始化。
一个类都会有默认的空参数的构造函数若指定了带参构造函数那么默认的空参数的构造函数就不存在了。
这时如果子类的构造函数有默认的super语句那么就会出现错误因为父类中没有空参数的构造函数。
因此在子类中默认super语句在父类中无对应的构造函数必须在子类的构造函数中通过this或super参数指定要访问的父类中的构造函数。
public class Main {public static void main(String[] args) {Student s new Student(Xiao Ming, 12, 89);}
}class Person {protected String name;protected int age;public Person(String name, int age) {this.name name;this.age age;}
}class Student extends Person {protected int score;public Student(String name, int age, int score) {this.score score;}
}
Error: Main.java:21: error: constructor Person in class Person cannot be applied to given types; public Student(String name, int age, int score) { ^ required: String,int found: no arguments reason: actual and formal argument lists differ in length 1 error error: compilation failed
运行上面的代码会得到一个编译错误大意是在Student的构造方法中无法调用Person的构造方法。
这是因为在Java中任何class的构造方法第一行语句必须是调用父类的构造方法。如果没有明确地调用父类的构造方法编译器会帮我们自动加一句super();所以Student类的构造方法实际上是这样
class Student extends Person {protected int score;public Student(String name, int age, int score) {super(); // 自动调用父类的构造方法this.score score;}
}但是Person类并没有无参数的构造方法因此编译失败。
解决方法是调用Person类存在的某个构造方法。例如
class Student extends Person {protected int score;public Student(String name, int age, int score) {super(name, age); // 调用父类的构造方法Person(String, int)this.score score;}
}这样就可以正常编译了
因此我们得出结论如果父类没有默认的构造方法子类就必须显式调用super()并给出参数以便让编译器定位到父类的一个合适的构造方法。
这里还顺带引出了另一个问题即子类不会继承任何父类的构造方法。子类默认的构造方法是编译器自动生成的不是继承的。