类中的java构造函数不能应用于给定的类型 [英] java constructor in class cannot be applied to given types
问题描述
我有2个子类:Staff,Student
他们属于超类Person。
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
}
}
我不知道为了创建没有参数的对象我可以键入什么。
它总是出现如下错误:构造函数类Person中的Person不能应用于给定的类型; required:java.lang.String,int;
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:
-
在超类中添加一个默认值:Person()//不带参数。
在子类Student:
add a default value in the superclass: Person()//without parameter. In the subclass Student:
Student()
{
Person astudent = new Student()/ /我猜。
}
在子类中添加super():
学生()
{
super(xxx)//我猜。
}
add a super() in the subclass:
Student()
{
super("xxx")//I guess.
}
我不知道该怎么做。我是学习BlueJ的先驱。
希望有人可以帮助我。非常感谢。
I don't know what to do. I an a starter in learning BlueJ. Hope anyone can help me. Thank you very much.
推荐答案
因为你的超级人
没有'在你的子类( Student
和 Staff
)中有一个默认构造函数,你必须调用超类构造函数第一个语句。
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
}
这篇关于类中的java构造函数不能应用于给定的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!