Java继承-子类不可以继承父类的构造方法
子類不可以繼承父類的構造方法,只可以調用父類的構造方法。
子類中所有的構造函數都會默認訪問父類中的空參數構造函數,這是因為子類的構造函數內第一行都有默認的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()并給出參數以便讓編譯器定位到父類的一個合適的構造方法。
這里還順帶引出了另一個問題:即子類不會繼承任何父類的構造方法。子類默認的構造方法是編譯器自動生成的,不是繼承的。
總結
以上是生活随笔為你收集整理的Java继承-子类不可以继承父类的构造方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2023全球最佳品牌排行榜公布 苹果第一
- 下一篇: java美元兑换,(Java实现) 美元