Objective-C Tutorial 2: Objective-C – Inheritance

Welcome to the second instalment of the series on introducing you to the world of Objective-C. In this article, we will talk about Objective-C Polymorphism concept of Inheritance. When writing classes, the importance is underlined in relationships between classes and objects,

The aim of being an efficient programmer is for code-reuse, and if you are coming from an existing OOP oriented background, like Java or C++, you know what i’m talking about, and therefore when we defined new classes, we form them in the mould of other classes, with slight differences, taking in the important properties of a parent class in addition to specialised specific code of your sub-class.

Screen_shot_2009-09-23_at_4

The removal of duplicated code by creating common code in the higher-up classes (superclasses), we can inherit the common code as well as specialise specific code. The inheritance syntax is:-

@interface Shape : NSObject
{
ShapeColor fillColor;
ShapeRect bounds;
}
- (void) setFillColor: (ShapeColor) fillColor;
- (void) setBounds: (ShapeRect) bounds;
- (void) draw;

@end

@implementation Shape

- (void) setFillColor: (ShapeColor) c {
fillColor = c;
}

- (void) setBounds: (ShapeRect) b
{
bounds = b; } // setBounds
}

- (void) draw { }
@end

Now, implementing the Circle, we would do:

@implementation Circle - (void) draw {
NSLog (@"drawing a circle at (%d %d %d %d) in %@", bounds.x, bounds.y,
bounds.width, bounds.height, colorName(fillColor));

} // draw
@end // Circle

As you can see, we can either override (by creating the same method as in your superclass) your parent class, or create new sub-class specific methods and inherit the superclass methods. To override, you would call [super methodName: param] to get all the properties of the parent before specialising.

Advertisements
This entry was posted in General and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s