Encapsulation

Encapsulation is one of the four pillars of Object Oriented Programming

There are two aspects to encapsulation.

The first is hinted at by the word. It is the process of encapsulating, or containing.

The aspect, although some OO purists argue with this, is the process of information hiding.

First the containment. An object, usually, contains both data and behaviour. Let's take, for example, a dog. If we create a class called dog it will contain some data. There will be, perhaps, fields or properties or both which show the dog's name, maybe its owner and the breed.

The class may also contain a method, which is OO speak for a function, which describes some behaviour. In this case we might have a method called bark. The question then arises, "What happens when we call the function, or invoke the method, bark. The method may contain code along the lines of: return "woof"

So when we create a new instance of dog we get an object which has the appropriate data and the behaviour. Our new dog will return "woof" when we call the method bark

All well and good. But now we get to the hiding bit. The code above which returned "woof" is called the implementation of the method bark. But that implementation is hidden from anyone or any object that calls the method. All we know is that we get back "woof", we don't know how we get it. And that is a big advantage because we can change the implementation without causing any difficulties anywhere else in the program.

For example. Suppose we have a database which contains a number of different types of barks. We might decide that they type of bark returned will depend upon the breed of dog. This would probably require two changes to implementations. One to the method bark and another to the property breed, but in both cases the changes would only occur in the dog class – no other classes, or clients, would know about it.

So, in this case when we set the property for the breed we would look up the breed table in the database. And the method for bark would now look something like this return breed.bark

Now if our dog is a Poodle it might bark with a "bow-wow". If it is Great Dane it might bark with a "Growl", and if it is a dog like my cross Border-Collie it might bark with a "Feed me".

So encapsulation enables us to put both data and behaviour into a class, and hence an object, and it also enables us to hide the way we implement that behaviour, and get the data, from outside classes.