4_Objective-C Data Encapsulation

Data encapsulation led to the important OOP concept of data hiding.

Encapsulation is an Object-Oriented Programming concept that binds together the data and functions that manipulate the data and that keeps both safe from outside interference and misuse.
Data encapsulation is a mechanism of bundling the data and the functions that use them.

Data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.

Example

@interface Adder : NSObject
{
    NSInteger total;
}
-(id)initWithInitialNumber:(NSInteger)initialNumber;
- (void)addNumber:(NSInteger)newNumber;
- (NSInteger)getTotal;
@end

The variable total is private and we cannot access from outside the class.

This means that they can be accessed only by other members of the Adder class and not by any other part of your program.

This is one way encapsulation is achieved.

  • Methods inside the interface file are accessible and are public in scope.
  • There are private methods, which are written with the help of extensions, which we will learn in upcoming chapters.
  • Any Objective-C program where you implement a class with public and private members variables is an example of data encapsulation and data abstraction.

Consider the following Example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: