Encapsulation is an overloaded expression, so let's define it first. According to Wikipedia encapsulation refers to two concepts:
In a programming language encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:
A language mechanism for restricting access to some of the object's components.
A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.
I would say that your typical JavaBeans class fulfills the second definition but almost never the first, so I guess the JavaBeans standard is not a good example of that particular notion of encapsulation.
Maybe slightly off topic, but explaining why something that starts with
class in your code is not necessarily always a
class in the more abstract sense.
I found a nice definition of
class and
data structure in
Clean Code. Unfortunately I don't have the book here, so I need to recite from the top of my head:
- A
class encapsulates its state, only offering sensible methods and exposing state only where it is necessary.
- A
data structure fully exposes its state, not trying to hide anything from the outside world
A class implemented according to the JavaBeans standard would be a data structure according to the definition above. That maybe explains why it is a class in code but actually not a class that fulfills encapsulation.