Home > Articles > Programming > General Programming/Other Languages

This chapter is from the book

This chapter is from the book

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 class—you 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.3Figure 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 else—for 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020