Concepts of Programming Languages

(Sean Pound) #1
12.6 Support for Object-Oriented Programming in Objective-C 551

There is another way to provide some of the benefits of multiple inheri-
tance in Objective-C, protocols. Although Objective-C does not provide
abstract classes, as in C++, protocols are related to them. A protocol is a list of
method declarations. The syntax of a protocol is exemplified with the following:

@protocol MatrixOps
-(Matrix *) add: (Matrix *) mat;
-(Matrix *) subtract: (Matrix *) mat;
@optional
-(Matrix *) multiply: (Matrix *) mat;
@end

In this example, MatrixOps is the name of the protocol. The add and
subtract methods must be implemented by a class that uses the protocol.
This use is called implementing or adopting the protocol. The optional part
specifies that the multiply method may or may not be implemented by an
adopting class.
A class that adopts a protocol lists the name of the protocol in angle brackets
after the name of the class on the interface directive, as in the following:

@interface MyClass: NSObject <YourProtocol>

12.6.3 Dynamic Binding


In Objective-C, polymorphism is implemented in a way that differs from the
way it is done in most other common programming languages. A polymorphic
variable is created by declaring it to be of type id. Such a variable can reference
any object. The run-time system keeps track of the class of the object to which
an id type variable refers. If a call to a method is made through such a vari-
able, the call is dynamically bound to the correct method, assuming one exists.
For example, suppose that a program has classes defined named Circle
and Square and both have methods named draw. Consider the following
skeletal code:

// Create the objects
Circle *myCircle = [[Circle alloc] init];
Square *mySquare = [[Square alloc] init];

// Initialize the objects
[myCircle setCircumference: 5];
[mySquare setSide: 5];

// Create the id variable
id shapeRef;

//Set the id to reference the circle and draw it
Free download pdf