Friends! I understood how setters, getters and designers work. But I did not understand one thing:

public class Person { private String name; public Person(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class User { public static void main(String[] args) { Person person = new Person("Василий"); System.out.println(person.getName()); person.setName("Леонид"); System.out.println(person.getName()); } } 

Why do we need setters if you can specify everything in the constructor (in the parameters)? Maybe there are some pitfalls or different situations?

  • four
    What will you do if the value of the properties becomes known much later than the creation of the object? What if different properties of an object are set in different parts of the code? What if the state of the object must change many times over the lifetime of the object? - Sergey Gornostaev
  • five
    @SergeyGornostaev is right. The name is given during the "creation" of a person so to speak. But after the age of majority, as far as I know, he can go to the passport office and change it. This is specifically for your code example - Aqua
  • More thanks to everyone, I understood everything !!! - Petrovchenko Ivan

2 answers 2

The constructor specifies the initial value. This method of initialization guarantees the setting of values ​​when creating an object and reduces the initialization code of this object (no need to additionally call setters). As a setter, the initial values ​​can be changed during the life of the object, otherwise it would have to create a new object through the constructor, which is often unacceptable. Well, getter, of course, get the current value

    When you pass the values ​​of certain fields in all constructors, you guarantee that these specific fields will be initialized. Networks do not provide such a guarantee. On the other hand, it is not always necessary, and therefore not always used.