Programming in C

(Barry) #1
Defining a C# Class to Work with Fractions 423

}
}


class example
{
public static void Main()
{
Fraction myFract = new Fraction();


myFract.Numerator = 1;
myFract.Denominator = 3;

myFract.print ();

}
}


Program 19.4 Output


The value of the fraction is 1/3


You can see the C# program looks a little different from the other two OOP programs,
but you can probably still determine what’s happening.The Fractionclass definition
begins by declaring the two instance variables numeratorand denominatoras private.
The Numeratorand Denominatormethods each have their getter and setter method
defined as properties.Take a closer look at Numerator:


public int Numerator
{
get
{
return numerator;
}


set
{
numerator = value;
}
}


The “get” code is executed when the value of the numerator is needed in an expression,
such as in


num = myFract.Numerator;


Program 19.4 Continued
Free download pdf