Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
This chapter is from the book

The @implementation Section

As noted, the @implementation section contains the actual code for the methods you declared in the @interface section. Just as a point of terminology, you say that you declare the methods in the @interface section and that you define them (that is, give the actual code) in the @implementation section.

The general format for the @implementation section is as follows:

@implementation NewClassName

NewClassName is the same name that was used for the class in the @interface section. You can use the trailing colon followed by the parent class name, as we did in the @interface section:

@implementation Fraction: NSObject

However, this is optional and typically not done.

The methodDefinitions part of the @implementation section contains the code for each method specified in the @interface section. Similar to the @interface section, each method's definition starts by identifying the type of method (class or instance), its return type, and its arguments and their types. However, instead of the line ending with a semicolon, the code for the method follows, enclosed inside a set of curly braces.

Consider the @implementation section from Program 3.2:

//---- @implementation section ----
@implementation Fraction
–(void) print
    NSLog (@"%i/%i", numerator, denominator);
–(void) setNumerator: (int) n
    numerator = n;

–(void) setDenominator: (int) d
    denominator = d;


The print method uses NSLog to display the values of the instance variables numerator and denominator. But to which numerator and denominator does this method refer? It refers to the instance variables contained in the object that is the receiver of the message. That's an important concept, and we return to it shortly.

The setNumerator: method stores the integer argument you called n in the instance variable numerator. Similarly, setDenominator: stores the value of its argument d in the instance variable denominator.

  • + Share This
  • 🔖 Save To Your Account