-2

I'm studying about encapsulation. We can create a fully encapsulated class in java by making all the data members of the class private.

We do that so that nobody else could access my class variables directly and change them.

For Example:

Class MyAccount{

int AccountTotalAmt = 1000;


}

Class Mainclass{

public static void main(String[] args){

MyAccount Obj = new MyAccount();

obj.AccountTotalAmt  = -200; (Just to avoid this kind of situations. Its just an example could be many more reasons)


}

}

Like I said , We do that because "nobody else could access my class variables directly and change them." To access them we make the variable private and set them using getter and setters. So what makes a difference here? What if someone knows these setters and getters as well? Can change them easily that way.

Is it a foolproof plan? Can anyone explain in a better way?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • you can put getters and setter as you want. I mean you can put validation in setters so that it will always validate when someone set the value. And also you can have only getters so that no one can change the value , only read the value – dwij Nov 26 '17 at 11:35

1 Answers1

0

So what's makes difference here ? What if someone knows these setters and getters as well ? Can change them easily that way.

The point here is once your fields are private you have complete control of who accesses the internal data. you decide whether to allow getters only or setters only or both. on top of that, you can also perform some validation within your setters to allow only valid data so it's not a matter of someone can change them easily.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • Thanks for sharing, Could you share any example how to restrict someone to access only getter but not setter method ? And how we can set only admin can control the full code but not the other user in java ? – Always Thinking Nov 26 '17 at 13:16