Concepts of Programming Languages

(Sean Pound) #1
11.4 Language Examples 493

would be named setSum. Assuming that sum is an int variable, these methods
could be defined as follows:


// The getter for sum
-(int) sum {
return sum;
}


// The setter for sum
-(void) setSum: (int) s {
sum = s;
}


If the getter and setter method for a particular variable does not impose
any constraints on their actions, they can be automatically generated by the
Objective-C compiler. This is done by listing the instance variables for which
getters and setters are to be generated on the property directive in the interface
section, as in the following:


@property int sum;


In the implementation section, the variables are listed in a synthesize direc-
tive, as in the following:


@synthesize sum;


Variables for which getters and setters are generated by the com-
piler are often called properties and the accessor methods are said to be
synthesized.
The getters and setters of instance variables can be used in two ways, either
in method calls or in dot notation, as if they were publically accessible. For
example, if we have defined a getter and a setter for the variable sum, they could
be used as in the following:


[myObject setSum: 100];
newSum = [myObject sum];


or as if they were publically accessible, as in the following:


myObject.sum = 100;
newSum = myObject.sum;


11.4.3.3 An Example


Following are the definitions of the interface and implementation of the stack
class in Objective-C:

Free download pdf