0

I am very new to java and I was just trying to get acclimatised to the syntax and there is one thing that I have been confused about. What is the difference between instantiating a new object in java then using the setname method to name it, and using a string parameter to assign a name in the constructor.

So if I have a class called Dog, what is the difference between, naming the dog by passing a name parameter onto its constructor and using setname under it. Are these processes different.

szulkifl
  • 1
  • 1
  • Yes, the two approaches are different. Though the way you specifically describe the hypothetical in your question means ultimately the two approaches are _effectively_ equivalent with respect to the end state of the object. But the constructor approach means the state is set during instantiation. This has the benefit of allowing for immutability (i.e., `final` fields, which can only be set during instantiation). The setter method can only be called after the object is instantiated/fully initialized (ignoring calling the method _from_ the constructor). It also requires mutability. – Slaw Jan 20 '23 at 23:07
  • Possibly a duplicate of [Setter methods or constructors](https://stackoverflow.com/questions/19359548/setter-methods-or-constructors). – Slaw Jan 20 '23 at 23:10

1 Answers1

0

Yes these are two differents things. You have to think about what exactly is your object and how he relates to his properties.

Constructor let you initialize the class variables dynamically at the time of instantiating the class so you should put the parameters without which the object would not be what it is (In the context of your code)

The setters methods are a totally different thing, it let you access variable to modify it. You should have setters when ,in your code, it make sense to modify a private variable.

If having a Dog without a name does not make sense in your code then add it as parameter in constructor. Can a Dog be renamed ? if yes, then add a setName method. Does your Dog have a default run speed that you can modify ? Then add a default speed variable in the class and setSpeed method.

Constructor are for parameters that make an object what it is and parameters that you always want to define when instanciating the object.

Setters are for modifying parameters after object was created.

loic .B
  • 281
  • 2
  • 11