Concepts of Programming Languages

(Sean Pound) #1

550 Chapter 12 Support for Object-Oriented Programming


members of the parent class are inherited by the subclass. New methods
and instance variables can be added to the subclass. Recall that all methods
are public, and that cannot be changed. A method that is defined in the sub-
class and has the same name, same return type, and same number and types
of parameters overrides the inherited method. The overridden method can be
called in another method of the subclass through super, a reference to the par-
ent object. There is no way to prevent the overriding of an inherited method.
As in Smalltalk, in Objective-C any method name can be called on any
object. If the run-time system discovers that the object has no such method
(with the proper protocol), an error occurs.
Objective-C does not support the private and protected derivations of C++.
As in other languages that support object-oriented programming, the con-
structor of an instance of a subclass should always call the constructor of the
parent class before doing anything else. If the name of the parent class con-
structor is init, this is done with the following statement:

[super init];

Objective-C includes two ways to extend a class besides subclassing:
categories and protocols. A collection of methods can be added to a class with
a construct called a category. A category is a secondary interface of a class that
contains declarations of methods. No new instance variables can be included in
the secondary interface. The syntactic form of such an interface is exemplified
by the following:

#import "Stack.h"
@interface Stack (StackExtend)
-(int) secondFromTop;
-(void) full;
@end

The name of this category is StackExtend. The original interface is accessible
because it is imported, so the parent class need not be mentioned. The new
methods are mixed into the methods of the original interface. Consequently,
categories are sometimes called mixins. Mixins are sometimes used to add
certain functionalities to different classes. And, of course, the class still has a
normal superclass from which it inherits members. So, mixins provide some of
the benefits of multiple inheritance, without the naming collisions that could
occur if modules did not require module names on their functions. Of course,
a category must also have an implementation section, which includes the name
of the category in parentheses after the class name on the implementation
directive, as in the following:

@implementation Stack (StackExtend)

The implementation need not implement all of the methods in the category.
Free download pdf