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
Remove void from your constructor.
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.
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){