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.
}
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.
Constructor X in Class Y Cannot be Applied to Given Types Just as with ordinary methods, constructors need to be invoked with the correct number, type, and order of arguments.
A static constructor is not allowed in Java programming. It is illegal and against the Java standards to use a static constructor. So, the Java program will not be compiled and throw a compile-time error.
Core Java bootcamp program with Hands on practice No, constructor does not have any return type in Java. Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. Mostly it is used to instantiate the instance variables of a class.
The child class inherits all the members of the superclass except the constructors. In other words, constructors cannot be inherited in Java therefore you cannot override constructors. So, writing final before constructors makes no sense. Therefore, java does not allow final keyword before a constructor.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With