Programming in C

(Barry) #1
Defining an Objective-C Class to Work with Fractions 417

The name of the new class is Fraction, and its parent class is Object.Classes inherit
methods and variables from their parents.
As you can see in the @interface section, the declarations


int numerator;
int denominator;


say that a Fractionobject has two integer members called numeratorand
denominator.
The members declared in this section are known as the instance variables. Each time
you create a new object, a new and unique set of instance variables is created.Therefore,
if you have two fractions, one called fracAand another called fracB, each has its own
set of instance variables.That is,fracAand fracBeach has its own separate numerator
and denominator.
You have to define methods to work with your fractions.You need to be able to set
the value of a fraction to a particular value. Because you don’t have direct access to the
internal representation of a fraction (in other words, direct access to its instance vari-
ables), you must write methods to set the numerator and denominator (these are known
as setters).You also need methods to retrieve the values of your instance variables (such
methods are known as getters).^1
The fact that the instance variables for an object are kept hidden from the user of the
object is another key concept of OOP known as data encapsulation.This assures someone
extending or modifying a class that all the code that accesses the data (that is, the
instance variables) for that class is contained in the methods. Data encapsulation provides
a nice layer of insulation between the programmer and the class developer.
Here’s what one such setter method declaration looks like:


-(int) numerator;


The leading minus sign (-) says that the method is an instance method.The only other
option is a plus sign (+), which indicates a class method. A class method is one that per-
forms some operation on the class itself, such as creating a new instance of the class.This
is similar to manufacturing a new car, in that the car is the class and you want to create a
new one—which would be a class method.
An instance method performs some operation on a particular instance of a class, such
as setting its value, retrieving its value, displaying its value, and so on. Referring to the
car example, after you have manufactured the car, you might need to fill it with gas.The
operation of filling it with gas is performed on a particular car, so it is analogous to an
instance method.


1.You canget direct access to the instance variables, but it’s generally considered poor program-
ming practice.

Free download pdf