codescracker


objective c

Objective-C Polymorphism



« Previous Tutorial Next Tutorial »


Polymorphism means having many forms. Generally, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.

Polymorphism in Objective-C means that a call to a member function will cause a different function to be executed, it depends on the object type that invokes the function.

Objective-C Polymorphism Example

Here is an example program, illustrating the concept of polymorphism in Objective-C. Let's suppose an example, where we have a class named Calmath, provides the basic interface for all the shapes. Square and Rectangle are derived from the base class, that is, Calmath. We have a method named display_area that is going to show about the object-oriented programming feature, polymorphism in Objective-C:

/* Objective-C Polymorphism - Example Program */
		
#import <Foundation/Foundation.h>

@interface Calmath : NSObject
{
	CGFloat area;
}

- (void)display_area;
- (void)calculate_area;
@end

@implementation Calmath
- (void)display_area
{
	NSLog(@"Area = %f", area);
}
- (void)calculate_area
{
}
@end

@interface Square : Calmath
{
	CGFloat len;
}
- (id)initWithSide:(CGFloat)side;
- (void)calculate_area;
@end

@implementation Square
- (id)initWithSide:(CGFloat)side
{
	len = side;
	return self;
}
- (void)calculate_area
{
	area = len * len;
}
- (void)display_area
{
	NSLog(@"Area of Square = %f", area);
}
@end

@interface Rectangle : Calmath
{
	CGFloat len;
	CGFloat bre;
}
- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth;
@end

@implementation Rectangle
- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth
{
	len = rLength;
	bre = rBreadth;
	return self;
}
- (void)calculate_area
{
	area = len * bre;
}
@end

int main(int argc, const char * argv[])
{
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	Calmath *square = [[Square alloc]initWithSide:10.0];
	[square calculate_area];
	[square display_area];
	Calmath *rect = [[Rectangle alloc]
	initWithLength:10.0 andBreadth:5.0];
	[rect calculate_area];
	[rect display_area];      
	[pool drain];
	
	return 0;
}

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

2014-10-03 21:21:50.785 Polymorphism[358:303] Area of Square = 100.000000
2014-10-03 21:21:50.786 Polymorphism[358:303] Area = 50.000000

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test