Data Encapsulation


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.

Leave a comment

4 Comments

  1. cgchinmay

     /  July 22, 2012

    If 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?

    Reply
    • Philosophically 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

      Reply
  1. Objects (Part 2): Properties « Programming for iOS
  2. Learn Objective-C in 24 Days « Programming for iOS

Leave a comment

  • Welcome

    My goal is to make CupsOfCocoa into a beautiful source for beginners to the iPhone platform to get started. Subscribe below for more, and stay tuned!

  • Contact Me

    If you need to contact me for any reason, feel free to send me an email.
  • The Giving Spirit

    If you've found this site helpful, would you consider donating a little sum? Any amount is appreciated...Thanks so much!

  • Roadmap

  • Enter your email address to follow this blog and receive notifications of new posts by email.

    Join 217 other subscribers
  • Back to the Past

    December 2010
    S M T W T F S
     1234
    567891011
    12131415161718
    19202122232425
    262728293031  
  • Time Machine

  • You count!

    • 625,652 views
  • Worldwide Stats

    free counters