Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

inheritance - java constructor in class cannot be applied to given types

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:

  1. add a default value in the superclass: Person()//without parameter.

    In the subclass Student:

Student()
  {
  Person astudent = new Student() //I guess.
  }
  1. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...