Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
715 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 Reply

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...