我有2个子类:工作人员,学生他们属于超级人物。
这是我的老师给出的代码(任务):
public class Person { private String name; private int yearOfBirth; /** * Create a person with given name and age. */ Person(String name, int yearOfBirth) { this.name = name; this.yearOfBirth = yearOfBirth; } }
class Student extends Person { private String SID; // student ID number /** * Create a student with no parameters. */ Student() { //task. } }
public class Staff extends Person { private String roomNumber; /** * Construct a staff member with field values and no pamaeters. */ public Staff() { //task } }
我不知道我能输入什么才能创建一个没有参数的对象。 它总是出现如下错误:构造函数类Person中的Person不能应用于给定的类型; required:java.lang.String,int;
我在网上查了一下,有两种方法可以解决这个问题:
在超类中添加一个默认值:Person()//不带参数。 在学生的子类中:
Student() { Person astudent = new Student() //I guess. }
在子类中添加一个super(): Student() { super("xxx")//I guess. } Student() { super("xxx")//I guess. }
我不知道该怎么办。 我是学习BlueJ的入门者。 希望任何人都可以帮助我。 非常感谢你。
I have 2 subclasses: Staff, Student they belong to superclass Person.
Here is the code(tasks) which is given by my teacher:
public class Person { private String name; private int yearOfBirth; /** * Create a person with given name and age. */ Person(String name, int yearOfBirth) { this.name = name; this.yearOfBirth = yearOfBirth; } }
class Student extends Person { private String SID; // student ID number /** * Create a student with no parameters. */ Student() { //task. } }
public class Staff extends Person { private String roomNumber; /** * Construct a staff member with field values and no pamaeters. */ public Staff() { //task } }
I don't know what can I type in order to create an object without parameter. It always appears an error like: constructor Person in class Person cannot be applied to given types; required: java.lang.String,int;
I have checked online that there are 2 ways to solve the problem:
add a default value in the superclass: Person()//without parameter. In the subclass Student:
Student() { Person astudent = new Student() //I guess. }
add a super() in the subclass: Student() { super("xxx")//I guess. }
I don't know what to do. I an a starter in learning BlueJ. Hope anyone can help me. Thank you very much.
最满意答案
由于您的超类Person没有默认构造函数,因此在您的子类( Student和Staff )中,必须调用超类构造函数作为第一条语句。
你应该像这样定义你的子类构造函数:
Student() { super("a_string_value", an_int_value);// You have to pass String and int values to super class }Staff() { super("a_string_value", an_int_value); // You have to pass String and int values to super class }
Since your super class Person doesn't have a default constructor, in your sub classes (Student and Staff), you must call the super class constructor as the first statement.
You should define your sub class constructors like this:
Student() { super("a_string_value", an_int_value);// You have to pass String and int values to super class }Staff() { super("a_string_value", an_int_value); // You have to pass String and int values to super class }
更多推荐
发布评论