我的代码与创建构造函数有什么问题? [英] What is wrong with my Code in relation to creating a constructor?

查看:108
本文介绍了我的代码与创建构造函数有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个Person类,用一个构造函数启动具有给定参数的实例变量,但是当通过主类创建一个新的person对象时,代码不能被编译,因为Person构造函数不需要参数,但我已经在构造函数中指定了四个。我使用NetBeans 7.2.1 ..这里是我的代码:

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


推荐答案

这不是一个构造函数;因为 void ,它是一个方法。

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

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

没有显式的构造函数,编译器创建一个默认的,没有arg的构造函数。这解释了错误消息的一部分:

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

移除 void 将其变成构造函数。

Remove the void to turn it into a constructor.

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

这篇关于我的代码与创建构造函数有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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