1

Concept of encapsulation:If we can change the value of private variable indirectly(through setters and getters), then how is the private variable secured, how is it hidden?Could someone please explain in detail..

  • 1
    What tells you can the setter changes a variable? Nothing. The class can ignore the setter. Encapsulation. – Boris the Spider Apr 10 '18 at 16:57
  • @BoristheSpider A setter is, by definition, changing a field. It's fair enough to sometimes have methods which mutable the state of an object, obviously, but someone whose relying on the Java bean pattern of getters and setters for every field is fooling themselves if they think they're encapsulating anything. – Michael Apr 10 '18 at 17:19

2 Answers2

2

You're correct. If a field is exposed via getters and setters, it is not encapsulated. It's annoying how many people don't understand this so it's not surprising that you're confused.

Michael
  • 41,989
  • 11
  • 82
  • 128
  • [This answer](https://stackoverflow.com/a/19044735/303810) states the exact opposite. – lexicore Apr 10 '18 at 17:04
  • @lexicore Yep. Because he's wrong. This article explains it best: http://www.yegor256.com/2016/11/21/naked-data.html – Michael Apr 10 '18 at 17:10
  • @lexicore Also check out [Is encapsulation still one of the elephants OOP stands on?](https://softwareengineering.stackexchange.com/questions/358611/is-encapsulation-still-one-of-the-elephants-oop-stands-on) – Vince Apr 11 '18 at 13:31
0

Check out this answer. Essentially, using the keyword private we are able to prevent outside use of the fields in a class, for example. It hides the data in a class associated with that private keyword.