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
111 views
in Technique[技术] by (71.8m points)

java - What is wrong with my Code in relation to creating a constructor?

I am trying to create a Person class, with a constructor that initiates the instance variables with the given parameters, but when a new person object is created through main class, the code can not be complied, as the Person constructors requires no arguments, but I have specified four in the constructor. I am using NetBeans 7.2.1.. here is my code:

public class Person {
    private String fName;
    private String mName;
    private String lName;
    private String dob;

    public void Person(String first, String middle, String last, String dateOfBirth){

        fName = first;
        mName = middle;
        lName = last;
        dob = dateOfBirth;
    }

    public String getFirstName(){
        return fName;
    }

    public String getMiddleName(){
        return mName;
    }

    public String getLastName(){
        return lName;
    }

    public String getDOB(){
        return dob;
    }

    public void getFullName(){
        System.out.println(fName + " " + mName + " " + lName);

    }

    public void setFirstName(String name){
        fName = name;
    }

    public void setMiddleName(String name){
        mName = name;
    }

    public void setLastName(String name){
        lName = name;
    }

    public void setDOB(String date){
        dob = date;
    }

    public static void main(String[] args) {
        Person p1 = new Person("John","Thomas","Smith", "10 Jul 14");
        p1.getFullName();
    }
}

This is the error I received when I ran the program:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code -       constructor Person in class Person cannot be applied to given types;
  required: no arguments
  found: java.lang.String,java.lang.String,java.lang.String,java.lang.String
  reason: actual and formal argument lists differ in length
    at Person.main(Person.java:54)
Java Result: 1
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This is not a constructor; because of void, it's a method.

public void Person(String first, String middle, String last, String dateOfBirth){

There was no explicit constructor, so the Java compiler created a default, no-arg constructor. That explains the part of the error message that states:

required: no arguments

Remove the void to turn it into a constructor.

public Person(String first, String middle, String last, String dateOfBirth){

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

...