-3

Why do I need a setter method when constructor handles assigning value to my private variable.

What's the difference?

public class Account {


private String name;


public Account(String name)
{
    this.name = name;
}

public void setName(String Name)
{
    this.name = name;
}

public String getName()
{
    return name + " is the best";
}
Bibek Shakya
  • 1,233
  • 2
  • 23
  • 45

3 Answers3

5

Constructors parameters are best for mandatory fields. You can't create the object without providing all the values required.

Named fields are better when they are optional, could be set in any order, you want to make it clear which field is what. Named fields also help avoid confusion when the types are the same and could be easily confused.

Notes:

  • these can be used on combination.
  • you can use a factory method or builder instead of calling the constructor directly.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

For Starter, you can use the constructor to set the value of your attribute at the point of instantiation your object but many case It will be problem for you because Object may have different value according to context they are put into.

After Constructor is used and Your Object is instantiated (Constructor are only once per Object) what if you need to change the value of an attribute. You can create new Object but it is waste of resources. If Dependency is not an option in your code then only go for constructor.

To meet the requirement of 4 principle of OOP, Getter and Setter method is the key to achieve it.

It depend on you design pattern too, for Immutable Object Creation, you have to use constructor because you cannot change state of the Object after it's creation.

Getter and Setter is the reason why Pojo Object are consider more powerful, when you have to code 100 of LOC which have numerous number of logic in it. But with the constructor you have to create constructor of different parameter according requirement that fulfill your logic that lead to number of dependencies toward class.

For future purpose, Constructor should only used for instantiating the object Like Single responsibility principle in SOLID.

Bibek Shakya
  • 1,233
  • 2
  • 23
  • 45
0

While the constructor can handle the job, the setter's function is to make the corresponding value mutable (externally) while with the constructor only it will be immutable unless it's public or changed internally.

Typically a value that isn't supposed to change (like IDs and such) is set by constructor and marked as final, while a value meant to be changed externally has a setter method to change the value as needed.

LordFokas
  • 68
  • 5