A central tenet of object-oriented programming is that the objects act as “black boxes”—that is, they hide, or encapsulate, their contents. When you call a method, you don’t care how the object does what you are asking it to do; you simply expect that the object will get the task done. The same concept applies to instance variables. The use of properties, and the accessor methods in particular, help to hide the instance variables themselves. You are indirectly accessing them; you get to control their access (such as making them readonly). By using methods, you also don’t have to worry about how the instance variables themselves are set up; you simply access the methods that are provided. An additional benefit of data encapsulation is that the creator of the class can change the internal workings (change the way the instance variables are set up, or the way a method operates) without breaking code that relies on the class. It’s like a car—most people don’t care how the car works, whether it burns gas or runs on gerbil power, as long as it gets them to the grocery store and back.
To be honest, it’s a difficult concept to explain; perhaps this page over at Stack Overflow (great site, BTW) does a better job.
cgchinmay
/ July 22, 2012If The ivars are declared as public,we dont need getter and setter methods to access them,every object would be able to change their values(by accessing them directly with dot operator) then why don’t we do this way?
Bruno Vieira
/ August 1, 2012Philosophically speaking, this modus operandi would violate the encapsulation, besides that there’s the fact that when you use properties or modify your iVars through methods defined by the OWNER class you are guaranteeing that the class is responsible alone for it’s own iVars which really doesn’t happen when your set everything to public. BTW, this is a good approach for android programming, but not for java and definitely not for Objective-C where modifiers are kind of obscure