codescracker


objective c

Objective-C Data Encapsulation



« Previous Tutorial Next Tutorial »


Encapsulation is a concept of object oriented programming, that binds together, the data and the functions, that manipulate the data and that keeps safe from outside interference and misuse.

Data encapsulation let to an important object-oriented programming concept of data hiding. Data encapsulation is simply a mechanism of bundling the data and the functions that use them, and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.

Let's take a look at the following code fragment

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

Here, the variable tot is private and can't access from outside the class. It means that they can be accessed only by the other members of the Summation class and not by any other part of your Objective-C program. This is a way encapsulation is achieved.

Objective-C Data Encapsulation Example

Here is an example program, illustrates the concept of data encapsulation in Objective-C:

/* Objective-C Data Encapsulation - Example Program */
		
#import <Foundation/Foundation.h>
@interface Summation : NSObject
{
	NSInteger tot;
}
- (id)initWithInitialNumber:(NSInteger)initialNumber;
- (void)addNumber:(NSInteger)newNumber;
- (NSInteger)getTotal;
@end

@implementation Summation
-(id)initWithInitialNumber:(NSInteger)initialNumber
{
	tot = initialNumber;
	return self;
}
- (void)addNumber:(NSInteger)newNumber
{
	tot = tot + newNumber;
}
- (NSInteger)getTotal
{
	return tot;
}
@end

int main(int argc, const char *argv[])
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	Summation *adder = [[Summation alloc]initWithInitialNumber:10];
	[adder addNumber:5];
	[adder addNumber:4];
	NSLog(@"Total = %ld",[adder getTotal]);
	[pool drain];
	
	return 0;
}

When the above code is compile and executed, it will produce the following result:

2014-10-03 21:17:30.485 DataEncapsulation[317:303] Total = 19

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test