I have to write a program which uses appropriate get and set methods to output the following: This person is John Smith (21, male)
So far, I have reached here:
public class Person {
private int age;
private String name;
private String gender;
public void setAge(int age){
this.age= age;
}
public int getAge(){
return age;
}
public void setName(String thename){
this.name=name;
}
public String getName(){
return name;
}
public void setGender(String gender){
this.gender= gender;
}
public String getGender(){
return gender;
}
public void person(){
System.out.printf("This person is %s(%d, %s)", getName(), getAge(), getGender());
}
}
In the main class:
class MyClass{
public static void main(String[] args) {
Person personObj1= new Person();
String thisname= "John Smith";
personObj1.setName(thisname);
personObj1.setAge(21);
String thisgender= "male";
personObj1.setGender(thisgender);
personObj1.person();
}
}
The problem is that I am getting errors like The method setName(String) is undefined for the type Person for the set methods in the main. I am still a beginner in Java so I have yet to get the hang of it.
The only problem I see is in the implementation of
setName
itself. You don't use the input variablethename
at all.The last line should be
But this would not give you the error you say you got (that
setName
doesn't exist). I'm guessing you either defined the actual method with all lowercase (likepublic void setname(String thename)
) or we are not seeing all of the code.