我的子类构造函数中的java构造函数错误
以下是作业:
使用以下准则设计和实现一个代表个人的类以及3个子类:
创建一个名为Person的类及其三个子类Employee、Student、Retired
b.此人有以下数据字段:姓名、出生年份、正在学习和受雇。它还提供了设置和获取每个字段值的方法,以及计算当前年龄和显示个人状态的方法。Person类中还包含一个将isStudying和isEmployed字段设置为false的构造函数。如果愿意,欢迎添加其他数据字段和方法
一,。最后,创建一个Java测试类,该类使用Person类进行模拟。在测试类中,您至少应该:a)构造4个个人实例,b)打印实例的名称c)根据实例的年龄、isStudying和isEmployed属性值打印实例的状态
public class Person2 {//begin class
//declare variables
String name;
int year_of_birth;
boolean isStudying;
boolean isEmployed;
int age;
public Person2(String name, int year_of_birth, boolean isEmployed, boolean isStudying, int age){//begin constructor
this.name = name;
this.year_of_birth = year_of_birth;
this.isEmployed = false;
this.isStudying = false;
this.age = age;
}//end constructor
public int getYear(){//get year method
return year_of_birth;
}//end method
public String getName(){//get name method
return name;
}//end method
public boolean getEmployed(){//get employed method
return isEmployed;
}//end method
public boolean getStudying(){//get employed method
return isStudying;
}//end method
public int getAge(){//get year method
age = 2014 - year_of_birth;
return age;
}//end method
public void setName(String name){//set name method
this.name = name;
}//end method
public void setYear (int year){//set year method
this.year_of_birth = year;
}//end method
public void setEmployed(boolean employed){//set employed method
this.isEmployed = employed;
}//end method
public void setAge (int age){//set year method
this.age = age;
}//end method
public static void main(String[] args) {
// TODO code application logic here
}
}
class Student extends Person2 {//begin class
public Student(String name, int year_of_birth, boolean isEmployed, boolean isStudying, int age){//begin constructor
this.name = name;
this.year_of_birth = year_of_birth;
this.isEmployed = isEmployed;
this.isStudying = isStudying;
this.age = age;
}//end constructor)
@Override
public int getYear(){//get year method
return year_of_birth;
}//end method
@Override
public String getName(){//get name method
return name;
}//end method
@Override
public boolean getEmployed(){//get employed method
return isEmployed = false;
}//end method
@Override
public boolean getStudying(){//get employed method
return isStudying = true;
}//end method
@Override
public int getAge(){//get year method
age = 2014 - year_of_birth;
if (age > 30){
System.out.println("Person is not a student");
}
return age;
}//end method
}
这段代码显然不完整,我被这个构造函数错误挂断了。它说“实际的和形式的争论在长度上是不同的”
# 1 楼答案
当扩展任何功能时,您应该尝试使用该功能
您的
class Student extends Person2
但是它是否使用了Person2
中的任何内容为什么要覆盖所有方法,并在子类中提供相同的功能
# 2 楼答案
问题是您没有调用超级构造函数
Person2
。您在Student
中的构造函数正在尝试调用Person2
的默认构造函数(没有参数),该构造函数不存在在
Person2
中只有一个构造函数,应该从Student
的构造函数调用该构造函数:这也意味着您不需要重复所有初始化代码两次
您也不应该重复
Student
中Person2
中的所有方法。如果将它们取出,Student
仍将继承它们。这就是扩展类的首要目的。如果您不想要继承的行为,而是想要一些特定于Student
的行为,那么应该重写这样的方法