Concepts of Programming Languages

(Sean Pound) #1

492 Chapter 11 Abstract Data Types and Encapsulation Constructs


Constructors in Objective-C are called initializers; they only provide ini-
tial values. They can be given any name, and as a result they must be explicitly
called. Constructors return a reference to the new object, so their type is always
a pointer to the class-name. They use a return statement that returns self, a
reference to the current object.
An object is created in Objective-C by calling alloc. Typically, after call-
ing alloc, the constructor of the class is explicitly called. These two calls can
be and usually are cascaded, as in the following statement, which creates an
object of Adder class with alloc and then calls its constructor, init, on the
new object, and puts the address of the new object in myAdder:

Adder *myAdder = [[Adder alloc]init];

All class instances are heap dynamic and are referenced through reference
variables.
C programs nearly always import a header file for input and output
functions, stdio.h. In Objective-C, a header file is usually imported that
has the prototypes of a variety of often required functions, including those
for input and output, as well as some needed data. This is done with the
following:

#import <Foundation/Foundation.h>

Importing the Foundation.h header file creates some data for the pro-
gram. So, the first thing the main function should do is allocate and initialize
a pool of storage for this data. This is done with the following statement:

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

Just before the return statement in main, this pool is released with a call to the
drain method of the pool object, as in the following statement:

[pool drain];

11.4.3.2 Information Hiding
Objective-C uses the directives, @private and @public, to specify the
access levels of the instance variables in a class definition. These are used as
the reserved words public and private are used in C++. The difference is
that the default in Objective-C is protected, whereas it is private in C++. Unlike
most programming languages that support object-oriented programming, in
Objective-C there is no way to restrict access to a method.
In Objective-C, the convention is that the name of a getter method for
an instance variable is the variable’s name. The name of the setter method is
the word set with the capitalized variable’s name attached. So, for a variable
named sum, the getter method would be named sum and the setter method
Free download pdf