In my previous post on the topic of Object Oriented Programming, I briefly touched on encapsulation as “A class is created by putting related things together (encapsulation) from which an object can be created. The programmer will encapsulate attributes and methods that are related to a particular object.”
This was my understanding from reading a previous text, however on reading Stephen Kochan’s Programming in Objective-C, he has made the subject of encapsulation easier to understand in relation the Objective-C language.
“What if you wanted to access your instance variables from someplace else – for example, from inside your main routine? You can’t do that directly because they are hidden. The fact that they are hidden from you is a key concept called data encapsulation…”.
He goes on to say “You can access your instance variables in a clean way by writing special methods to set and retrieve their values”, and describes the theory of setters and getters, and how to set them up manually. As I have already worked through some chapters of an iOS programming book, I have already come across setters and getters, however did not realise their relevance to the subject of encapsulation.
With regards to setting the setters and getters manually, Steve does this so that you learn the theory, as later in the book he will go on to describe the @property and @synthesize statements for setting up the setters and getters easier.