Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 38 ยท Objects and Classes

Inheritance and Polymorphism

Learn single inheritance in Objective-C, overriding methods, calling super, polymorphism with id and base class pointers, abstract class patterns and design guidance.

Inheritance lets a new class reuse and extend an existing one. A Dog is an Animal, so it can inherit everything an animal does and add or change what is specific to dogs. Polymorphism is the payoff: code written for Animal works unchanged with any subclass, because the correct method is chosen at run time. Objective-C supports single inheritance only: every class has exactly one superclass, and NSObject sits at the root.

Declaring a subclass

OBJECTIVEC
@interface Animal : NSObject
@property (nonatomic, copy) NSString *name;
- (instancetype)initWithName:(NSString *)name;
- (void)speak;
@end

@implementation Animal
- (instancetype)initWithName:(NSString *)name {
    self = [super init];
    if (self) { _name = [name copy]; }
    return self;
}
- (void)speak {
    NSLog(@"%@ makes a sound", self.name);
}
@end

@interface Dog : Animal
@property (nonatomic, assign) BOOL trained;
- (void)fetch;
@end

@implementation Dog
- (void)speak {                  // override
    NSLog(@"%@ says woof", self.name);
}
- (void)fetch {
    NSLog(@"%@ fetches the ball", self.name);
}
@end

Dog inherits name, initWithName: and speak, adds trained and fetch, and replaces speak. Ivars are inherited, but a subclass cannot see the superclass's @private ones or ones declared in its .m; it uses the properties and methods instead.

Overriding and calling super

A subclass overrides a method by implementing one with the same selector. Often you want to add to the behaviour rather than replace it, so call super:

OBJECTIVEC
@implementation Dog
- (void)speak {
    [super speak];                // Animal's version first
    NSLog(@"(and wags its tail)");
}
@end

For initializers, call the superclass's designated initializer first. For dealloc under ARC, do not call super.

Return types and parameter types of an override must match the original.

Polymorphism

Because a Dog is an Animal, a variable of type Animal * may point at a Dog. Which speak runs depends on the actual object, not on the variable's declared type:

OBJECTIVEC
NSArray<Animal *> *zoo = @[
    [[Animal alloc] initWithName:@"Generic"],
    [[Dog alloc] initWithName:@"Rex"],
    [[Cat alloc] initWithName:@"Tom"],
];
for (Animal *a in zoo) {
    [a speak];          // each object responds in its own way
}

This works because the runtime looks the selector up in the receiver's own class first, then in its superclasses. The declared type only governs what the compiler lets you write. To use a subclass-only method, check and cast:

OBJECTIVEC
if ([a isKindOfClass:[Dog class]]) {
    [(Dog *)a fetch];
}

You could also declare the variable as id and send any message, but the compiler stops checking; prefer a specific type or protocols (the next chapter).

Class hierarchy

flowchart TB
  NSObject --> Animal
  Animal --> Dog
  Animal --> Cat
  Dog --> Puppy

Single inheritance forms a tree rooted at NSObject. [puppy isKindOfClass:[Animal class]] is true.

Useful NSObject methods

  • [obj class] and [Dog superclass] navigate the hierarchy.
  • isKindOfClass: includes subclasses; isMemberOfClass: does not.
  • isEqual: and hash compare objects, and you must override both consistently when equality should depend on content.
  • description provides the text that %@ prints.

Abstract classes

Objective-C has no abstract keyword. A class intended only as a base documents that its methods must be overridden, and fails loudly if they are not:

OBJECTIVEC
@implementation Shape
- (double)area {
    [NSException raise:NSInternalInconsistencyException
                format:@"%@ must override %@", NSStringFromClass([self class]),
                       NSStringFromSelector(_cmd)];
    return 0;
}
@end

Protocols (next chapter) often express "must implement" better than an abstract base class does.

Method overriding rules of thumb

  • Keep the Liskov substitution principle: a subclass must work wherever its superclass is expected.
  • Prefer composition ("has a") over inheritance ("is a") when the relationship is not a true "is a".
  • Avoid deep hierarchies of more than three levels.
  • Do not override methods whose contract you do not understand; read the class documentation (for example, NSArray is a class cluster and is not safe to subclass directly).

Stand-in: overriding by replacing a table entry

In C, you can model inheritance by embedding the base struct first and giving each class its own table of function pointers (a "vtable"). A subclass copies its parent's table and replaces the entries it overrides. Calling through the table is polymorphism.

C Stand-in (C): vtable-based overriding and polymorphism

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: abstract method and a class-chain test

C Stand-in (C): abstract area() and isKindOfClass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Forgetting to call [super ...] in an override that must extend behaviour (such as viewDidLoad or init).
  • Changing a method's signature in a subclass; it then becomes a different selector.
  • Casting without checking with isKindOfClass:.
  • Using inheritance only to share code, where composition fits better.
  • Subclassing class clusters like NSArray or NSString without knowing their rules.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many superclasses can an Objective-C class have?

    Objective-C supports single inheritance. Multiple contracts are expressed with protocols.
  2. 2. Animal *a = [[Dog alloc] init]; [a speak]; Which speak runs?

    Dispatch is dynamic: the receiver's class is searched first.
  3. 3. What is the usual way to extend an inherited method instead of replacing it?

    super starts the lookup in the superclass, running its implementation.
  4. 4. How do you create an abstract-like method in Objective-C?

    There is no abstract keyword; base methods raise an error and protocols describe required methods.

Summary

  • A subclass inherits properties and methods, adds its own, and overrides with the same selector.
  • [super method] runs the superclass version; use it to extend rather than replace.
  • Polymorphism: the receiver's real class decides which implementation runs.
  • Use isKindOfClass: before casting to a subclass.
  • Prefer composition and protocols over deep hierarchies; Objective-C has no abstract keyword.

Next: Class Methods and Singletons