错误构造函数Family(String,String,int)未定义

我对Java很陌生。我收到错误消息“构造函数Family(String,String,int)未定义”。我不确定这是什么意思。请在这里需要一些帮助。

Main.java

public class Main {


public static void main(String[] args){
    Family person = new Family("CHRIS", "PEREZ", 31);
    String person1 = person.getPerson();
    System.out.println(person1);    
}

}

家庭.java

public class Family {

String firstName;
String lastName;
int age;
int phoneNumber;
String dob;
String married;

public Family(String firstName, String lastName, int age, int phoneNumber,
        String dob, String married) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.phoneNumber = phoneNumber;
    this.dob = dob;
    this.married =  married;


public String getPerson() {
    return ("Hi my name is"+this.firstName+" "+ this.lastName+"."+"I am "+this.age+" years old.");
}

}
评论
  • pnon
    pnon 回复

    This is because your Family class only has a six-argument constructor requiring all of the six fields to be provided. Your call:

    Family person = new Family("CHRIS", "PEREZ", 31);
    

    仅提供所需的六个中的三个。您可以覆盖构造函数,例如:

    public Family(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        ...
    }
    

    但是您应该对其他构造函数中未提供的其余字段进行处理。

  • 本明远
    本明远 回复

    您正在调用此构造函数:

    Family person = new Family("CHRIS", "PEREZ", 31);
    

    但是构造函数的定义如下:

    public Family(String firstName, String lastName, int age, int phoneNumber,
        String dob, String married) {
    

    See that it has more parameters than you're passing in: phoneNumber, dob, married. In Java you have to give values to all parameters:

    Family person = new Family("CHRIS", "PEREZ", 31, 123456, "5/Apr/1975", "who's asking");
    

    或者,您需要定义一个仅需要firstName,lastName和age的新构造函数。