What is the difference between setter methods and constructor methods?

killaclipss :
public class Person
{
    private String name;
    private String streetAddress;
    private String cityStateZip;

    public Person()
    {
        name = "John Doe";
        streetAddress = "55 Main Street";
        cityStateZip = "Anywhere, MA 00001";
    }

    public Person(String n, String s, String c)
    {
        name = n;
        streetAddress = s;
        cityStateZip = c;
    }
    public String getName()
    {
        return this.name;
    }
    public void setName()
    {
    this.name = name;
    }
    public String getStreetAddress()
    {
        return this.streetAddress;
    }
    public void setStreetAddress()
    {
        this.streetAddress = streetAddress;
    }
    public String getCityStateZip()
    {
        return this.cityStateZip;
    }
    public void setCityStateZip()
    {
        this.cityStateZip = cityStateZip;
    }
    public String toString()
    {
        String str =    name + "\n" + streetAddress + "\n" + cityStateZip + "\n";
        return str;
    }

}

In the code above I have written a class that will create a person object and will be used to create other classes that will implement this person class. While I was writing this superclass I thought, what is the difference between setter methods and constructors? Are setter methods simply helpful because you can easily just do .set(methodName) or? Would someone be willing to explain the difference between my constructor and my setter method?

0x476f72616e :

Constructors construct new object, where as setters are created to update that object.

So lets say your name is Ding Dong and you live at, and you create a person object with your name and following address.

12345 15th Street
Area 51, Nevada 12345

and you move couple of blocks down the street to:

1234 15th Street
Area 51, Nevada 12345

Well you do not need to create new Person object because you moved, you just need to update address. That is where you will use setter method.

Conclusion: Setters are there to update your record and constructors are there to create new Person object.

I hope this helps!!!!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87362&siteId=1