Java: set and get methods for strings

5.2k views Asked by At

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.

1

There are 1 answers

2
Always Learning On BEST ANSWER

The only problem I see is in the implementation of setName itself. You don't use the input variable thename at all.

public void setName(String thename){

    this.name=name;
}

The last line should be

this.name = thename;

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 (like public void setname(String thename)) or we are not seeing all of the code.