Here a simple example of how inheritance works in objective-c (based on this older example).
1. Define the parent class.
Rectangle.h
#import <Foundation/NSObject.h> @interface Rectangle: NSObject @property (nonatomic) int width; @property (nonatomic) int height; -(Rectangle*) initWithWidth: (int) w height: (int) h; -(void) setWidth: (int) w height: (int) h; -(void) print; @end
Rectangle.m
#import "Rectangle.h" #import <stdio.h> @implementation Rectangle @synthesize width = _width; @synthesize height = _height; -(Rectangle*) initWithWidth: (int) w height: (int) h { self = [super init]; if ( self ) { [self setWidth: w height: h]; } return self; } -(void) setWidth: (int) w height: (int) h { self.width = w; self.height = h; } -(void) print { printf( "width = %i, height = %i", self.width, self.height ); } @end
2. Inherit from the parent.
Here we inherit our behavior from the parent with this line:
@interface Square: Rectangle <strong>Square.h</strong> #import "Rectangle.h" @interface Square: Rectangle -(Square*) initWithSize: (int) s; -(void) setSize: (int) s; -(int) size; @end
And add our own customer behaviour:
Square.m
#import "Square.h" @implementation Square -(Square*) initWithSize: (int) s { self = [super init]; if ( self ) { [self setSize: s]; } return self; } -(void) setSize: (int) s { self.width = s; self.height = s; } -(int) size { return self.width; } @end
You can see here we inherit the Rectangle’s setWidth setHeight and print methods while providing our own setSize implementation.
3. Run it.
SpikeInheritanceTests.m
#import "SpikeInheritanceTests.h" #import "Square.h" #import "Rectangle.h" #import <stdio.h> @implementation SpikeInheritanceTests - (void)testExample { Rectangle *rec = [[Rectangle alloc] initWithWidth: 10 height: 20]; Square *sq = [[Square alloc] initWithSize: 15]; // print em printf( "Rectangle: " ); [rec print]; printf( "\n" ); printf( "Square: " ); [sq print]; printf( "\n" ); // update square [sq setWidth: 20]; printf( "Square after change: " ); [sq print]; printf( "\n" ); } @end
If all goes well output should look something like this:
Leave a Reply