Skip to content

Instantly share code, notes, and snippets.

@rajiv-singaseni
Created July 13, 2011 18:55
Show Gist options
  • Save rajiv-singaseni/1081023 to your computer and use it in GitHub Desktop.
Save rajiv-singaseni/1081023 to your computer and use it in GitHub Desktop.
An objective C example demonstrating the concept of inheritance.
//
// Animal.h
// InheritanceDemo
//
// Created by Rajiv on 14/07/2011.
// Copyright 2011 WebileApps. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Animal : NSObject {
}
-(void) shout;
-(void) noOfEyes;
-(void) doSomeTask;
@end
@interface Dog : Animal {
}
//A parent method which is over ridden in child.
-(void) shout;
//A new method belonging to this class.
-(void) swim;
//Another function overridden in child class
-(void) doSomeTask;
@end
//
// Animal.m
// InheritanceDemo
//
// Created by Rajiv on 14/07/2011.
// Copyright 2011 Webile Apps. All rights reserved.
//
#import "Animal.h"
@implementation Animal
-(void) shout {
NSLog(@"Animal: Not sure how does I shout");
}
-(void) noOfEyes {
NSLog(@"Animal: I have 2 eyes");
}
-(void) doSomeTask {
NSLog(@"Animal: I am doing some task");
}
@end
@implementation Dog
-(void) shout {
NSLog(@"Dog: Wow wow..");
}
-(void) swim {
NSLog(@"Dog: I am swimming");
}
-(void) doSomeTask {
[super doSomeTask];
NSLog(@"Dog: I am doing some task");
}
@end
2011-07-14 00:35:05.572 InheritanceDemo[84631:207] Animal: Not sure how does I shout
2011-07-14 00:35:05.573 InheritanceDemo[84631:207] Animal: I am doing some task
2011-07-14 00:35:05.574 InheritanceDemo[84631:207] Animal: I have 2 eyes
2011-07-14 00:35:05.575 InheritanceDemo[84631:207] Dog: Wow wow..
2011-07-14 00:35:05.575 InheritanceDemo[84631:207] Dog: I am swimming
2011-07-14 00:35:05.576 InheritanceDemo[84631:207] Animal: I have 2 eyes
2011-07-14 00:35:05.576 InheritanceDemo[84631:207] Animal: I am doing some task
2011-07-14 00:35:05.577 InheritanceDemo[84631:207] Dog: I am doing some task
-(void) someFunction {
Animal *animal = [[Animal alloc] init];
[animal shout];
[animal doSomeTask];
// [animal swim]; //Generates comile time errors
[animal noOfEyes];
Dog *dog = [[Dog alloc] init];
[dog shout];
[dog swim];
[dog noOfEyes];
[dog doSomeTask];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment