JAVA构造函数的继承

时间:2023-03-10 01:22:52
JAVA构造函数的继承

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