1、子類中無參構造函數,可直接繼承父類中無參構造函數,前提是所有變量均為public
如下:父類Student中有空構造函數Student(),子類Pupil中有空構造函數Pupil(),后者會繼承前者。
注:在本例中,父類中的name、height都是public的,如果是private就無法直接繼承。
package javastudy; public class ConfunDemo5 { public static void main(String[] args) { Pupil z=new Pupil(); z.show(); } } class Student{ //父類Student public String name; public int height; public Student() { this.name=""; this.height=0; } } class Pupil extends Student{ //子類Pupil private int score; public Pupil(){ //無參構造函數Pupil()直接繼承了父類中的無參構造函數Student() score=0; } public void show(){ System.out.print("姓名:"+name+"\n身高:"+height+"\n分數:"+score); } }
輸出:
姓名:
身高:0
分數:0
2、子類中無參構造函數繼承父類中無參構造函數時,父類參數是private的,無法直接
需要在父類中使用get方法來調用私有變量值。
package javastudy; public class ConfunDemo5 { public static void main(String[] args) { Pupil z=new Pupil(); z.show(); } } class Student{ //父類Student private String name; private int height; public Student() { this.name=""; this.height=0; } public String getName(){ return name; } public int getHeight(){ return height; } } class Pupil extends Student{ //子類Pupil private int score; public Pupil(){ //無參構造函數Pupil()直接繼承了父類中的無參構造函數Student(),但是父類中的name、height是private的 score=0; } public void show(){ System.out.print("姓名:"+getName()+"\n身高:"+getHeight()+"\n分數:"+score); //輸出時,直接用get方法名。 } }
3、使用super調用父類的構造函數
super必須寫在方法的首行
package javastudy; public class ConfunDemo5 { public static void main(String[] args) { Pupil z=new Pupil("隔壁老王",111,222); z.show(); Pupil w=new Pupil(); w.show(); } } class Student{ //父類Student public String name; public int height; public Student() { this.name=""; this.height=0; } public Student(String n,int m) { name=n; height=m; } } class Pupil extends Student{ //子類Pupil private int score; public Pupil(){ super("孫悟空2",501); //使用super調用父類Student(String n,int m)方法,同時傳遞實際數值。super必須寫在方法的首行。如果這里寫super(),則調用的是父類中的Student()方法。 score=0; } public Pupil(String x,int y,int z){ // super(x,y); //使用super調用父類Student(String n,int m)方法,其中super中的參數名稱必須與構造函數中的參數名稱一致。 score=z; } public void show(){ System.out.println("姓名:"+name+"\n身高:"+height+"\n分數:"+score); } }
輸出:
姓名:隔壁老王
身高:111
分數:222
姓名:孫悟空2
身高:501
分數:0