codescracker


objective c

Objective-C Dynamic Binding



« Previous Tutorial Next Tutorial »


In Objective-C, dynamic binding determines the method to invoke/call at the runtime of the program, instead at the compile time of the program.

All the methods in Objective-C, are resolved dynamically at the program runtime. And the exact code executed is determined through the method name and the receiving object both.

Objective-C Dynamic Binding Example

Here is an example program, demonstrates the dynamic binding in Objective-C.

/* Objective-C Dynamic Binding - Example Program */
		
#import <Foundation/Foundation.h>
@interface SQUARE:NSObject
{
	float area;
}
- (void)calculate_area_of_side:(CGFloat)side;
- (void)print_area;
@end

@implementation SQUARE
- (void)calculate_area_of_side:(CGFloat)side
{
	area = side * side;
}
- (void)print_area
{
	NSLog(@"The area of square = %f", area);
}
@end

@interface RECTANGLE:NSObject
{
	float area;
}
- (void)calculate_area_of_length:(CGFloat)length andBreadth:(CGFloat)breadth;
- (void)print_area;
@end

@implementation  RECTANGLE
- (void)calculate_area_of_length:(CGFloat)length andBreadth:(CGFloat)breadth
{
	area = length * breadth;
}
- (void)print_area
{
	NSLog(@"The area of Rectangle = %f", area);
}
@end

int main()
{
	SQUARE *square = [[SQUARE alloc]init];
	[square calculate_area_of_side:10.0];
	RECTANGLE *rectangle = [[RECTANGLE alloc]init];
	[rectangle calculate_area_of_length:10.0 andBreadth:5.0];
	NSArray *shapes = [[NSArray alloc]initWithObjects: square, rectangle,nil];
	id object1 = [shapes objectAtIndex:0];
	[object1 print_area];
	id object2 = [shapes objectAtIndex:1];
	[object2 print_area];
	
	return 0;
}

Now when we compile and run the above program, then we will get the following output:

2015-10-03 07:42:29.821 demo[4916] The area of square = 100.000000
2015-10-03 07:42:29.821 demo[4916] The area of Rectangle = 50.000000

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test