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

前端 未结 3 1373
走了就别回头了
走了就别回头了 2020-12-12 02:59

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 mai

相关标签:
3条回答
  • 2020-12-12 03:42

    Remove void from your constructor.

    0 讨论(0)
  • 2020-12-12 03:47

    Change your code to be this:

    public class Person {
        private String fName;
        private String mName;
        private String lName;
        private String dob;
    
        public 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();
        }
    }
    

    Explanation:

    Constructors don't have a return type. The "return type" for a constructor is a new instance of the class, and that doesn't have to be defined.

    When you define a return type on a constructor you make it into a method. If there are no other constructors, Java will use a default zero-argument constructor. That is why you get the error.

    0 讨论(0)
  • 2020-12-12 03:48

    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){
    
    0 讨论(0)
提交回复
热议问题