The program section contains the code to solve your particular
problem, which can be spread out across many files, if necessary.
Somewhere you
must have a routine called main, as we've previously noted.
That's where your program always begins execution.
Here is the program
section from Program 3.2:
//------- program section ------- int main (int argc, char *argv[]) { Fraction *myFraction; // Create an instance of a Fraction myFraction = [Fraction alloc]; myFraction = [myFraction init]; // Set fraction to 1/3 [myFraction setNumerator: 1]; [myFraction setDenominator: 3]; // Display the fraction using the print method printf ("The value of myFraction is:"); [myFraction print]; printf ("\n"); [myFraction free]; return 0; }
Inside main you define a variable called myFraction with the following line:
Fraction *myFraction;
This line says that myFraction is an object of type Fraction; that is, myFraction is used to store values from your new Fraction class. The asterisk (*) in front of myFraction is required, but don't worry about its purpose now. Technically, it says that myFraction is actually a reference (or pointer) to a Fraction.
Now that you have an object to store a Fraction, you need to create one, just like you ask the factory to build you a new car. This is done with the following line:
myFraction = [Fraction alloc];
alloc is short for allocate. You want to allocate memory storage space for a new fraction. The expression
[Fraction alloc]
sends a message to your newly created Fraction class. You are asking the Fraction class to apply the alloc method, but you never defined an alloc method, so where did it come from? The method was inherited from a parent class. Chapter 8 deals with this topic in detail.
When you send the alloc message to a class, you get back a new instance of that class. In Program 3.2, the returned value is stored inside your variable myFraction. The alloc method is guaranteed to zero out all of an object's instance variables. However, that does not mean that the object has been properly initialized for use. You need to initialize an object after you allocate it.
This is done with the next statement in Program 3.2, that reads as follows:
myFraction = [myFraction init];
Again, you are using a method here that you didn't write yourself. The init method initializes the instance of a class. Note that you are sending the init message to myFraction. That is, you want to initialize a specific Fraction object here, so you don't send it to the classyou send it to an instance of the class. Make sure you understand this point before continuing.
The init method also returns a value, namely the initialized object. You take the return value and store it in your Fraction variable myFraction.
The two-line sequence of allocating a new instance of class and then initializing it is done so often in Objective-C that the two messages are typically combined, as follows:
myFraction = [[Fraction alloc] init];
The inner message expression
[Fraction alloc]
is evaluated first. As you know, the result of this message expression is the actual Fraction that is allocated. Instead of storing the result of the allocation in a variable as you did before, you directly apply the init method to it. So, again, first you allocate a new Fraction and then you initialize it. The result of the initialization is then assigned to the myFraction variable.
As a final shorthand technique, the allocation and initialization is often incorporated directly into the declaration line, as in the following:
Fraction *myFraction = [[Fraction alloc] init];
This coding style is used often throughout the remainder of this book, so it's important that you understand it.
Returning to Program 3.2, you are now ready to set the value of your fraction. The program lines
// Set fraction to 1/3 [myFraction setNumerator: 1]; [myFraction setDenominator: 3];
do just that. The first message statement sends the setNumerator: message to myFraction. The argument that is supplied is the value 1. Control is then sent to the setNumerator: method you defined for your Fraction class. The Objective-C system knows that it is the method from this class to use because it knows that myFraction is an object from the Fraction class.
Inside the setNumerator: method, the passed value of 1 is stored inside the variable n. The single program line in that method takes that value and stores it in the instance variable numerator. So, you have effectively set the numerator of myFraction to 1.
The message that invokes the setDenominator: method on myFraction follows next. The argument of 3 is assigned to the variable d inside the setDenominator: method. This value is then stored inside the denominator instance variable, thus completing the assignment of the value 1/3 to myFraction. Now you're ready to display the value of your fraction, which is done with the following lines of code from Program 3.2:
// display the fraction using the print method printf ("The value of myFraction is:"); [myFraction print]; printf ("\n");
The first printf call simply displays the following text:
The value of myFraction is:
A newline is not appended to the end of the line so that the value of the fraction as displayed by the print method appears on the same line. The print method is invoked with the following message expression:
[myFraction print];
Inside the print method, the values of the instance variables numerator and denominator are displayed, separated by a slash character. The final printf call back in main simply displays a newline character.
The last message in the program,
[myFraction free];
frees the memory that was used for the Fraction object. This is a critical part of good programming style. Whenever you create a new object, you are asking for memory to be allocated for that object. Also, when you're done with the object, you are responsible for releasing the memory it uses. Although it's true that the memory will be released when your program terminates anyway, after you start developing more sophisticated applications, you can end up working with hundreds (or thousands) of objects that consume a lot of memory. Waiting for the program to terminate for the memory to be released is wasteful of memory, can slow your program's execution, and is not good programming style. So, get into the habit right now!
It seems as if you had to write a lot more code to duplicate in Program 3.2 what you did in Program 3.1. That's true for this simple example here; however, the ultimate goal in working with objects is to make your programs easier to write, maintain, and extend. You'll realize that later.
The last example in this chapter shows how you can work with more than one fraction in your program. In Program 3.3, you set one fraction to 2/3, set another to 3/7, and display them both.
Program 3.3
// Program to work with fractions cont'd #import <stdio.h> #import <objc/Object.h> //------- @interface section ------- @interface Fraction: Object { int numerator; int denominator; } -(void) print; -(void) setNumerator: (int) n; -(void) setDenominator: (int) d; @end //------- @implementation section ------- @implementation Fraction; -(void) print { printf (" %i/%i ", numerator, denominator); } -(void) setNumerator: (int) n { numerator = n; } -(void) setDenominator: (int) d { denominator = d; } @end //------- program section ------- int main (int argc, char *argv[]) { Fraction *frac1 = [[Fraction alloc] init]; Fraction *frac2 = [[Fraction alloc] init]; // Set 1st fraction to 2/3 [frac1 setNumerator: 2]; [frac1 setDenominator: 3]; // Set 2nd fraction to 3/7 [frac2 setNumerator: 3]; [frac2 setDenominator: 7]; // Display the fractions printf ("First fraction is:"); [frac1 print]; printf ("\n"); printf ("Second fraction is:"); [frac2 print]; printf ("\n"); [frac1 free]; [frac2 free]; return 0; }
Program 3.3 Output
First fraction is: 2/3 Second fraction is: 3/7
The @interface and @implementation sections remain unchanged from Program 3.2. The program creates two Fraction objects called frac1 and frac2 and then assigns the value 2/3 to the first fraction and 3/7 to the second. Realize that, when the setNumerator: method is applied to frac1 to set its numerator to 2, the instance variable frac1 gets its instance variable numerator set to 2. Also, when frac2 uses the same method to set its numerator to 3, its distinct instance variable numerator is set to the value 3. Each time you create a new object, it gets its own distinct set of instance variables. This is depicted in Figure 3.3.
Figure 3.3 Unique instance variables.
Based on which object is getting sent the message, the correct instance variables are referenced. Therefore, in
[frac1 setNumerator: 2];
it is frac1's numerator that is referenced whenever setNumerator: uses the name numerator inside the method. That's because frac1 is the receiver of the message.
Accessing Instance Variables and Data Encapsulation
You've seen how the methods that deal with fractions can access the two instance variables numerator and denominator directly by name. In fact, an instance method can always directly access its instance variables. A class method can't, however, because it's dealing only with the class itself and not with any instances of the class (think about that for a second). But what if you wanted to access your instance variables from someplace elsefor example, from inside your main routine? You can't do that directly because they are hidden. The fact that they are hidden from you is a key concept called data encapsulation. It enables someone writing class definitions to extend and modify his class definitions without worrying about whether programmers (that is, users of the class) are tinkering with the internal details of the class. Data encapsulation provides a nice layer of insulation between the programmer and the class developer.
You can access your instance variables in a clean way by writing special methods to retrieve their values. For example, you'll create two new methods called, appropriately enough, numerator and denominator to access the corresponding instance variables of the Fraction that is the receiver of the message. The result will be the corresponding integer value, which you will return. Here are the declarations for your two new methods:
-(int) numerator; -(int) denominator; And here are the definitions: -(int) numerator { return numerator; } -(int) denominator { return denominator; }
Note that the names of the methods and the instance variables they access are the same. There's no problem doing this; in fact, it is common practice. Program 3.4 tests your two new methods.
Program 3.4
// Program to access instance variables cont'd #import <stdio.h> #import <objc/Object.h> //------- @interface section ------- @interface Fraction: Object { int numerator; int denominator; } -(void) print; -(void) setNumerator: (int) n; -(void) setDenominator: (int) d; -(int) numerator; -(int) denominator; @end //------- @implementation section ------- @implementation Fraction; -(void) print { printf (" %i/%i ", numerator, denominator); } -(void) setNumerator: (int) n { numerator = n; } -(void) setDenominator: (int) d { denominator = d; } -(int) numerator { return numerator; } -(int) denominator { return denominator; } @end //------- program section ------- int main (int argc, char *argv[]) { Fraction *myFraction = [[Fraction alloc] init]; // Set fraction to 1/3 [myFraction setNumerator: 1]; [myFraction setDenominator: 3]; // Display the fraction using our two new methods printf ("The value of myFraction is: %i/%i\n", [myFraction numerator], [myFraction denominator]); [myFraction free]; return 0; }
Program 3.4 Output
The value of myFraction is 1/3
The printf statement
printf ("The value of myFraction is: %i/%i\n", [myFraction numerator], [myFraction denominator]);
displays the results of sending two messages to myFraction: the first to retrieve the value of its numerator, and the second the value of its denominator.
Incidentally, methods that set the values of instance variables are often collectively referred to as setters, and methods used to retrieve the values of instance variables are called getters. For the Fraction class, setNumerator: and setDenominator: are the setters and numerator and denominator are the getters.
It should also be pointed out here that there is also a method called new that combines the actions of an alloc and init. So, the line
Fraction *myFraction = [Fraction new];
could be used to allocate and initialize a new Fraction. It's generally better to use the two-step allocation and initialization approach so you conceptually understand that two distinct events are occurring: You're first creating a new object and then you're initializing it.
Now you know how to define your own class, create objects or instances of that class, and send messages to those objects. We'll return to the Fraction class in later chapters. You'll learn how to pass multiple arguments to your methods, how to divide your class definitions into separate files, and also about key concepts such as inheritance and dynamic binding. However, now it's time to learn more about data types and writing expressions in Objective-C. First, try the exercises that follow to test your understanding of the important points covered in this chapter.