类中的 java 构造函数不能应用于给定类型 [英] java constructor in class cannot be applied to given types

查看:57
本文介绍了类中的 java 构造函数不能应用于给定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个子类:职员、学生它们属于超类 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 不能应用于给定类型;必需: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:

  1. 在超类中添加一个默认值:Person()//没有参数.

在子类 Student 中:

In the subclass Student:

Student()
  {
  Person astudent = new Student() //I guess.
  }

  1. 在子类中添加一个 super():

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.

推荐答案

由于您的超类 Person 没有默认构造函数,因此在您的子类 (StudentStaff),则必须调用超类构造函数作为第一条语句.

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆