-6

Why it is important to make mutable data members of a Java class private?

What consequences does this have, and how do we commonly get around them?

Appreciate any help. Have been googling around but I've only came across answers that explain how to create an immutable class etc.

John
  • 2,395
  • 15
  • 21
  • Otherwise other classes can modify your private implementation details and the class that owns the member won't even know about it. This can break all your invariants, all the guarantees you expect to hold true inside that class. – Louis Wasserman Aug 05 '16 at 06:22
  • thanks louis, what about the consequences and how to get around the consequences? – yappyhappy Aug 05 '16 at 07:41
  • No real way to get around the consequences except not to expose those members in the first place. Make them private and make the type immutable. It's the only way. – Louis Wasserman Aug 05 '16 at 15:35

2 Answers2

0

'Private' keyword is saying everything. it's good habit to make data member of mutable class private because it is safe and secure. No one can access those member directly. In a application, so many challenges come regarding safe and secure application. this kind of application require to data member make safe and secure by 'Private'.

vimal suthar
  • 61
  • 1
  • 6
  • There was a quote that we all have private parts but it is not always appropriate to expose them – Dr Phil May 28 '19 at 03:18
0

I'd like to attempt answering this question as this is part of my mock-exam question.

its important to make mutable data members private so that other classes or the main class will not be making direct changes to the data members in the class without going through the necessary logic processing within the class.

in some scenarios, say entering a String based data member called name, the data to be inserted into the data member may require validation and processing before it can be stored within the object for integrity of use later on with other classes.

the consequence is that any changes made to the data member requires the class itself to make those changes. no other classes have access to add,modify or remove values from the data members within the class.

the common work-around the consequence is to create the necessary get and set methods for each of the data members.

joke
  • 121
  • 1
  • 6
  • oh yes, i also think this post adds value to the answer - https://softwareengineering.stackexchange.com/questions/143736/why-do-we-need-private-variables – joke Dec 03 '18 at 07:50