Is this example of Polymorphism wrong?
ios, objective-c, polymorphism
Solution
You are correct, that example doesn't illustrate polymorphism. This is how they should've written the example.
#import <Foundation/Foundation.h>
//PARENT CLASS FOR ALL THE SHAPES
@interface Shape : NSObject
{
CGFloat area;
}
- (void)printArea;
- (void)calculateArea;
@end
@implementation Shape
- (void)printArea{
NSLog(@"The area is %f", area);
}
- (void)calculateArea
{
NSLog(@"Subclass should implement this %s", __PRETTY_FUNCTION__);
}
@end
@interface Square : Shape
{
CGFloat length;
}
- (id)initWithSide:(CGFloat)side;
@end
@implementation Square
- (id)initWithSide:(CGFloat)side{
length = side;
return self;
}
- (void)calculateArea{
area = length * length;
}
- (void)printArea{
NSLog(@"The area of square is %f", area);
}
@end
@interface Rectangle : Shape
{
CGFloat length;
CGFloat breadth;
}
- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth;
@end
@implementation Rectangle
- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth{
length = rLength;
breadth = rBreadth;
return self;
}
- (void)calculateArea{
area = length * breadth;
}
@end
int main(int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Shape *shape_s = [[Square alloc]initWithSide:10.0];
[shape_s calculateArea]; //shape_s of type Shape, but calling calculateArea will call the
//method defined inside Square
[shape_s printArea]; //printArea implemented inside Square class will be called
Shape *shape_rect = [[Rectangle alloc]
initWithLength:10.0 andBreadth:5.0];
[shape_rect calculateArea]; //Even though shape_rect is type Shape, Rectangle's
//calculateArea will be called.
[shape_rect printArea]; //printArea of Rectangle will be called.
[pool drain];
return 0;
}
Problem
I'm trying to get my head around polymorphism, my understanding is that it means that you can have the same method across multiple classes and at runtime the correct version will be called based on the type of the object it's being invoked on. This example below, states: http://www.tutorialspoint.com/objective_c/objective_c_polymorphism.htm "Objective-C polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function." In the example both square and rectangle are subclasses of shape which both implement their own calculateArea method, I'm assuming it's this method that's being used to demonstrate the polymorphism concept. They call 'calculateArea' on a Square object and squares calculateArea method is called, then they call 'caculateArea on a Rectangle object and rectangles 'calculateArea method is called. It can't be that simple, surely this is obvious, square doesn't even know about rectangles 'calculateArea' which is in a completely different class so couldn't ever possibly be confused about which version of the method to use. What am I missing?