TweetFollow Us on Twitter

The Road to Code: You Have Your Mother's Eyes

Volume Number: 24 (2008)
Issue Number: 01
Column Tag: The Road to Code

The Road to Code: You Have Your Mother's Eyes

Inheritance and Polymorphism

by Dave Dribin

From Rectangles to Circles

Last month in The Road to Code, we started writing Objective-C code, and we ended up writing a class that represents a geometric rectangle. I'll list it here for those who skipped out last month:

Listing 1: Last month's Rectangle.h

#import <Foundation/Foundation.h>
@interface Rectangle : NSObject
{
   float _leftX;
   float _bottomY;
   float _width;
   float _height;
}
- (id) initWithLeftX: (float) leftX
          bottomY: (float) bottomY
           rightX: (float) rightX
            topY: (float) topY;
- (void) setRightX: (float) rightX;
- (float) area;
- (float) perimeter;
@end

Listing 2: Last month's Rectangle.m

#import "Rectangle.h"
@implementation Rectangle
- (id) initWithLeftX: (float) leftX
          bottomY: (float) bottomY
           rightX: (float) rightX
            topY: (float) topY
{
   self = [super init];
   if (self == nil)
      return nil;
   
   _leftX = leftX;
   _bottomY = bottomY;
   _width = rightX - leftX;
   _height = topY - bottomY;
   
   return self;
}
- (void) setRightX: (float) rightX
{
   _width = rightX - _leftX;
}
- (float) area
{
   return _width * _height;
}
- (float) perimeter
{
   return (2*_width) + (2*_height);
}
@end

We also wrote a simple program that uses this new class:

Listing 3: Last month's main.m

#import <Foundation/Foundation.h>
#import "Rectangle.h"
int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool =
      [[NSAutoreleasePool alloc] init];
   Rectangle * rectangle;
   
   rectangle = [Rectangle alloc];
   rectangle = [rectangle initWithLeftX: 5
                         bottomY: 5
                          rightX: 15
                           topY: 10];
   
   printf("Area is %.2f\n", [rectangle area]);
   printf("Perimeter is: %.2f\n", [rectangle perimeter]);
   
   [rectangle setRightX: 20];
   printf("Area is %.2f\n", [rectangle area]);
   printf("Perimeter is: %.2f\n", [rectangle perimeter]);
   
   [rectangle release];
   
   [pool release];
   return 0;
}

Now, let's say we also want a class that represents a geometric circle. And let's also say we want to have methods that calculate the area and perimeter, just like our rectangle class. As a quick refresher on circle geometry, I refer you to Figure 1:


Figure 1: Geometric circle

From this diagram, we can see the circle has a center point of (10, 5) and a radius (r) of 3. Here are the equations for area and perimeter:

Area = π x r2 = π x 3 x 3 = 28.27

Perimeter = 2 x π x r = 2 x π x 3 = 18.85

We will design our data structure to keep track of the center point and the radius. The header file for a Circle class is defined in Listing 4.

Listing 4: Circle.h, first attempt

#import <Foundation/Foundation.h>
@interface Circle : NSObject
{
   float _centerX;
   float _centerY;
   float _radius;
}
- (id) initWithCenterX: (float) centerX
            centerY: (float) centerY
            radius: (float) radius;
- (float) area;
- (float) perimeter;
@end

This class has instance variables for the center point and radius, and the constructor allows us to create a circle using these values, too. The area and perimeter method declarations are identical to those in the header of our rectangle class. Now let's look at the implementation of this circle class:

Listing 5: Circle.m, first attempt

#import "Circle.h"
#import <math.h>
@implementation Circle
- (id) initWithCenterX: (float) centerX centerY: (float) centerY
            radius: (float) radius
{
   self = [super init];
    if (self == nil)
        return nil;
   _centerX = centerX;
   _centerY = centerY;
   _radius = radius;
   return self;
}
- (float) area
{
   return M_PI * _radius * _radius;
}
- (float) perimeter
{
   return 2 * M_PI * _radius;
}
@end

Okay, that's fairly straightforward, too. The only new part is the M_PI constant, which is value of π and is defined in math.h, which we have imported. Now, let's take the main function we used to test out our rectangle class and adapt it to our circle class:

Listing 6: main.m to test Circle

#import <Foundation/Foundation.h>
#import "Rectangle.h"
#import "Circle.h"
int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool =
   [[NSAutoreleasePool alloc] init];
   
   Circle * circle;
   circle = [[Circle alloc] initWithCenterX: 10
                            centerY: 5
                             radius: 3];
   
   
   printf("Area is %.2f\n", [circle area]);
   printf("Perimeter is %.2f\n", [circle perimeter]);
   
   [circle release];
   
   [pool release];
   return 0;
}

This is very similar to the Rectangle test program in Listing 3. The only change I made was to chain the alloc and initWithCenterX:centerY:radius: method calls together on one line. Method chaining, i.e., calling a method on an object returned from another method call, is often done for object initialization like this. You will almost always see the alloc/init combo chained together. If we run this, it should produce the output:

Area is 28.27
Perimeter is 18.85

Inheritance

This is all well and good, but now, let's mix it up a bit. Let's say we want to mix rectangles and circles in one application and print out the area of both of them. The simplest way to accomplish this is to just have two separate printf statements, like this:

Rectangle * rectangle; rectangle = [[Rectangle alloc] initWithLeftX: 5 bottomY: 5 rightX: 15 topY: 10]; Circle * circle; circle = [[Circle alloc] initWithCenterX: 10 centerY: 5 radius: 3]; printf("Area is %.2f\n", [rectangle area]); printf("Area is %.2f\n", [circle area]);

This should get us the following output:

Area is 50.00
Area is 28.27

If we are printing the area a lot, we would want to put this into a separate function called, say printShapeArea. However, we run into a bit of a snag. How can we write one function that can print the area of rectangles and circles? It turns out we can by writing a printShapeArea function with the following signature:

void printShapeArea(NSObject * shape);

You'll notice that our function takes a shape of type NSObject *. You've seen NSObject before in the header files for our classes, but I've just glossed over it. Take the first line of the Rectangle class as an example:

@interface Rectangle : NSObject

It turns out that classes are organized into a hierarchy, sort of like a family tree. Every class we create must have one parent and can have zero or more children. The word after the colon allows us to provide the name of the parent class. Thus, this line says that we are creating a new class named Rectangle with a parent class of NSObject. Conversely, this means that Rectangle is a child class of NSObject. Our Circle class is declared very similarly, with its parent class also as NSObject.

There's also some fancy object-oriented terminology for these family relationships. The parent class is called the superclass, while a child class is called a subclass. To confuse the matter, a superclass is also known as a base class, and a subclass is known as a derived class. We can draw out the relationships between classes in a diagram that looks a bit like a family tree. This diagram is called a class hierarchy, and it would look like Figure 2 for our Rectangle and Circle classes. The little triangle points to the parent and indicates that the classes below are subclasses.


Figure 2: Class hierarchy

Looking at this diagram, it's clear that both Rectangle and Circle share NSObject as an ancestor. It's this common superclass that allows us to use NSObject * as the type used for the printShapeArea function. Remember that Objective-C, like C, is a statically typed language. This means that parameters to all functions and methods are given a type, and the compiler will complain if you try to pass an object of a different type to that function or method. However - and this is a distinguishing point of object-oriented programming - anytime a function or method requires a certain class, you can always pass any subclass without conversion. This means, for example, that a function that takes a parameter of type NSObject * can be passed any subclass of NSObject without conversion. Since both Rectangle and Circle are derived from NSObject, they may both be passed to printShapeArea without conversion. Thus, we can replace the printf calls in our main function with:

   printShapeArea(rectangle);
   printShapeArea(circle);

However, the implementation of printShapeArea gets a little tricky. This is because the automatic type conversion for related classes is one-way only. You can only automatically convert to superclasses, or up the class hierarchy, but you cannot automatically convert to a subclass. Let me show you the implementation, and then we will walk through it:

Listing 7: printShapeArea

void printShapeArea(NSObject * shape)
{
   float area = 0;
   if ([shape isKindOfClass: [Rectangle class]])
   {
      Rectangle * rectangle = (Rectangle *) shape;
      area = [rectangle area];
   }
   else if ([shape isKindOfClass: [Circle class]])
   {
      Circle * circle = (Circle *) shape;
      area = [circle area];
   }
   printf("Area is %.2f\n", area);
}

The tricky part about converting to a subclass is we don't know what kind of class the variable shape is. It could be a Rectangle or it could be a Circle, we just don't know. However, we can ask an object what kind of class it is an instance of, and that's what the isKindOfClass: method is doing. Asking an object about its type at runtime is called introspection. First, we ask if it is a Rectangle class. If it is, we convert the generic shape to a rectangle using this syntax:

      Rectangle * rectangle = (Rectangle *) shape;

This conversion syntax is called a cast. The problem is that casting an object from one type to another is very dangerous. You're basically overriding the compiler and saying "Yes, this shape really is a rectangle," and it will blindly trust you. If, for some reason, this is not a Rectangle, you will most likely crash your program. But we can get away with a cast here because we just asked the object if it was, indeed, a Rectangle. Because it said "yes," we know we can perform that cast safely. Once we perform the cast, we can call the area method to find out the rectangle's area.

If the object is not a Rectangle class, we then ask if it is a Circle class. If it is, we do a similar cast to the Circle class, and then call the circle's area method. Finally, we print the area, which we got from either the rectangle or the circle. And voila! We have our generic printShapeArea function. Pass in any shape, and it will print the area.

It's worth noting that the methods defined in a superclass are available to all subclasses. Just as real-world children inherit traits from their parents, classes inherit methods from their superclasses. That's also why subclassing is also referred to as inheritance. We just demonstrated why this is useful. You'll notice we used the isKindOfClass: method. But where did this method come from? We didn't define it in our Rectangle class, but it is inherited from NSObject. I've said before that all objects are descendants of NSObject. NSObject provides a lot of base functionality that all these subclasses inherit, including features such as memory management and introspection. We'll get to see more of NSObject's features in later articles.

Polymorphism

Looking at the printShapeArea function in Listing 7 with a critical eye, we'll see a couple of issues. First, it's a fair amount of code. What we gain in flexibility, we lose in readability. However, the real issue is that it's not even that flexible. Sure, we can pass in either a Rectangle or Circle, but what if we create a new shape, say Triangle, which can also calculate its area? Now we have to modify our function to check for the Triangle class. In fact, every time we add any new shape, we'd need to update this function. That's a fragile situation, and it's not a good property of well-designed code.

The second issue is that there's nothing stopping us from passing a non-shape object to this function. Remember that NSObject is the common ancestor of all objects. It doesn't make sense to pass in a number object such as NSNumber, because it doesn't have the area method. Even though Objective-C is statically typed, it won't properly detect this condition with our current implementation.

To solve both of these issues, we can create a new, intermediate Shape class. This is a subclass of NSObject, but it will be the superclass of both Rectangle and Circle. The first step is to create the Shape class, with no implementation. The empty header is presented in Listing 8 and the empty implementation in Listing 9.

Listing 8: Empty Shape.h

#import <Cocoa/Cocoa.h>
@interface Shape : NSObject
{
}
@end

Listing 9: Empty Shape.m

#import "Shape.h"
@implementation Shape
@end

Now, we make this the superclass of Rectangle by changing its @interface line to:

@interface Rectangle : Shape

And similarly, we make Shape the superclass of Circle by changing its @interface line to:

@interface Circle : Shape

By subclassing Shape like this, our class hierarchy now looks like Figure 3.


Figure 3: Class hierarchy with Shape

Finally, we change the signature of printShapeArea to:

void printShapeArea(Shape * shape)

This solves the problem of passing a non-shape object to printShapeArea. If we tried to pass a number object, the compiler will now warn us. It will allow Rectangle and Circle because both are subclasses of Shape, and can be converted to Shape due to the inheritance hierarchy. However, this doesn't actually reduce the amount of code or allow us to avoid casting. We can achieve this by another refinement to the Shape class.

You'll notice that the area method for Rectangle and Circle both have the same signature: no arguments and return a float. Because this method signature is exactly the same, we can add an area method to the Shape class. What should we do for the implementation? Since an unknown shape has an undefined area, let's just return 0.

Now we have a very interesting situation. We've defined the area method in both a superclass and subclass. With two different implementations, which one gets chosen when [rectangle area] gets called? The rule is that the deepest implementation in the class hierarchy wins. Thus, in this case, Rectangle's area trumps Shape's area, and Rectangle is said to override the area method. Method overriding is an important feature of object-oriented programming, and every OO language should allow you to do this.

Overriding plays a very important role, though. You'll notice that both Rectangle and Circle override Shape's area method. So what's the point of having this method, then, if it will never get called? It allows us to simplify printShapeArea, by removing the introspection calls and casting:

void printShapeArea(Shape * shape)
{
   float area = [shape area];
   printf("Area is %.2f\n", area);
}

Now at first glance, you might think that this will always print "Area is 0.00" even when passed a Rectangle or Circle instance. After all, the Shape implementation always returns 0. However, through the magic of OO, this actually prints the correct results:

Area is 50.00
Area is 28.27

How is this possible? It turns out that even though shape is of type Shape in our code, the object really is still a Rectangle or Circle at heart. Method calls take into account what type the object really is, instead of what type the code says. In fact, Objective-C won't figure out which area method will be called until we actually run the program. This magic is called polymorphism. It is also sometimes referred to as late binding since the method call is not bound until the actual invocation of the method at runtime, not compile time.

The immediate benefits of polymorphism are readily apparent. All of our introspection and casting code goes away and printShapeArea becomes a two-line function. However, the benefits go deeper. By using polymorphism, we can add a Triangle class with an area method and printShapeArea will still work, as is. As long as Triangle inherits from Shape, we don't have to modify the source code to printShapeArea at all. Better yet, printShapeArea can be compiled into a library prior to the existence of Triangle, and it will work due to the runtime binding. This is powerful stuff, and it is a cornerstone of OO programming.

In addition to the area method, we can add the perimeter method to the Shape class. Again, its implementation should return 0, as it is intended to be overridden by subclasses. This will allow us to create a printShapePerimeter function in a similar vein to the printShapeArea function. By doing this, we are saying a shape must be able to calculate its area and perimeter. Our final Shape class should look like the code in Listing 10 and Listing 11.

Listing 10: Shape.h

#import <Foundation/Foundation.h>
@interface Shape : NSObject
{
}
- (float) area;
- (float) perimeter;
@end
Listing 11: Shape.m
#import "Shape.h"
@implementation Shape
- (float) area
{
   return 0;
}
- (float) perimeter
{
   return 0;
}
@end

For the sake of completeness, Listing 11 is the accompanying main.m:

Listing 11: main.m

#import <Foundation/Foundation.h>
#import "Shape.h"
#import "Rectangle.h"
#import "Circle.h"
void printShapeArea(Shape * shape);
int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool =
   [[NSAutoreleasePool alloc] init];
   
   Rectangle * rectangle;
   rectangle = [[Rectangle alloc] initWithLeftX: 5
                               bottomY: 5
                                rightX: 15
                                 topY: 10];
   Circle * circle;
   circle = [[Circle alloc] initWithCenterX: 10
                            centerY: 5
                             radius: 3];
   
   
   printShapeArea(rectangle);
   printShapeArea(circle);
   
   [rectangle release];
   [circle release];
   
   [pool release];
   return 0;
}
void printShapeArea(Shape * shape)
{
   float area = [shape area];
   printf("Area is %.2f\n", area);
}

Protocols

Our geometric shape class library is progressing nicely. We've got classes for rectangles and circles, as well as a common base class for future extensibility. New shapes can be added and, through the magic of polymorphism, the code impact is minimal. However, if you're a perfectionist, the area and perimeter methods of Shape may be bothering you. Their sole purpose is more of a placeholder for subclasses than doing anything useful. Sometimes, you have to live with a bit of ugliness due to the limitations of the language. However, Objective-C provides a better alternative. Instead of making Shape a class, we can make it a protocol. A protocol is like a class with only an interface and no implementation. It's used to specify a common set of methods that a class must implement. Our Shape class transformed to a protocol would need only the Shape.h header file shown in Listing 13.

Listing 12: Shape.h for a protocol

#import <Foundation/Foundation.h>
@protocol Shape
- (float) area;
- (float) perimeter;
@end

This looks similar to our previous class header file in Listing 11. We use the @protocol keyword and there is no area to define instance variables. Protocols are not allowed to have instance variables. If you need 'em, you'll have to use a class. To use this protocol in our Rectangle class, we use a bit of new syntax in the @interface line:

@interface Rectangle : NSObject<Shape>

This states that Rectangle is now a subclass of NSObject again, however by putting Shape in the angle brackets, we're declaring that Rectangle implements the Shape protocol. This means that we must implement all methods in this protocol. We already do this, so we don't have to make any further modifications to Rectangle. We can make similar modifications to Circle to make it implement the Shape protocol, too.

We must now change our printShapeArea function, since the Shape class no longer exists. In order to get the benefit of static type checking we must declare the function as follows:

void printShapeArea(NSObject<Shape> * shape);

This says that printShapeArea accepts an NSObject, but not just any old NSObject: only NSObjects that implement the Shape protocol. So now we've really got the ultimate solution. We've got our type safety, we've got our polymorphism, and we've got no useless code. The implementation is the same as before:

void printShapeArea(NSObject<Shape> * shape)
{
   float area = [shape area];
   printf("Area is %.2f\n", area);
}

It's worth noting that protocols can also inherit from other protocols, similar to class inheritance. For example, we could create a DrawableShape protocol that inherits from the Shape protocol:

@protocol DrawableShape <Shape>
- (void) draw;
@end

Any object that implements the DrawableShape protocol must implement all three methods: area, perimeter, and draw.

Conclusion

Inheritance and polymorphism are the final pillars of object-oriented programming. Along with the concepts of classes and encapsulation, you're well on your way to becoming an OO guru. With these OO building blocks under your belt, we can start getting into the details of Objective-C and the standard class libraries. I hope you join me next month in The Road to Code.


Dave Dribin has been writing professional software for over eleven years. After five years programming embedded C in the telecom industry and a brief stint riding the Internet bubble, he decided to venture out on his own. Since 2001, he has been providing independent consulting services, and in 2006, he founded Bit Maki, Inc. Find out more at http://www.bitmaki.com/ and http://www.dribin.org/dave/.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.