State and Behavior
Learn why encapsulation is an important idea.
We'll cover the following
Data and methods
Let’s have another look at our class definition for Person
:
class Persondef initialize(name)@name = nameenddef name@nameenddef password=(password)@password = passwordendend
Our class demonstrates an important thing about objects: There’s a way to ask a person for their name
, but no way to set a new name. On the other hand, there’s a way to set a new password, but no way to ask for it.
Hopefully, this seems clear at this point.
Encapsulation
People tend to offer their name freely but keep their passwords secret. The same is true for objects.
Every object has its own object scope that might hold several instance variables. These are private to the object. Our person
object knows their password once it’s given to them. From then on, though, they won’t tell anyone the password because there’s no method designed for sharing this private information. On the other hand, there’s a name
method, which is an attribute reader, so we can ask our person
object for their name. There’s no way for others to give a new name to the person because there’s no method for that. There’s no name=
attribute writer.
This concept is called encapsulation, and it’s one of the main motivations behind the whole paradigm of object-oriented programing:
We can say that an object encapsulates state (data, knowledge), which is private to the object, and exposes behavior by way of having publicly accessible methods.
Remember: Objects have state (instance variables) and behavior (methods).
So, we’ve now created our first little class, and it’s one that we could actually see in a real application.