-2

I thought the set method was used to specify the attribute of an object, but in the following class, the set method Unused for balance attribute .Why is the set method used for the name attribute but not the set method for the balance sample variable?

enter image description here

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • Does this answer your question? [Why use getters and setters/accessors?](https://stackoverflow.com/questions/1568091/why-use-getters-and-setters-accessors) – ΔO 'delta zero' Dec 20 '21 at 19:33
  • It's simply the designer's choice that they want to prevent users of the class from directly setting the balance. To me, this class looks like it's a design in progress. There is a `deposit` method but no `withdraw` method defined yet. Maybe the author will add a `setBalance` method later. – Tenfour04 Dec 20 '21 at 20:07

1 Answers1

1

the constructor validates if the balance is > 0, and then the depositAmount method is used to "set" increase the instance variable.

Also you wouldn't want a public method to directly set the value of a private balance variable, this way the balance value is safely controlled through a public method.

If you had a set method for balance you could then do something like

account_object = new Account("Bob",-5)

it would create the obj with name Bob and balance 0, then you could

account_object.setBalance(-100)

and bypass the validations set (balance > 0)

There is no constraint on name so its fine to have a method that can set it directly.

B.Quinn
  • 77
  • 1
  • 7