20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Def<strong>in</strong><strong>in</strong>g a C# Class to Work with Fractions<br />

423<br />

Program 19.4<br />

}<br />

}<br />

Cont<strong>in</strong>ued<br />

class example<br />

{<br />

public static void Ma<strong>in</strong>()<br />

{<br />

Fraction myFract = new Fraction();<br />

myFract.Numerator = 1;<br />

myFract.Denom<strong>in</strong>ator = 3;<br />

myFract.pr<strong>in</strong>t ();<br />

}<br />

}<br />

Program 19.4 Output<br />

The value of the fraction is 1/3<br />

You can see the C# program looks a little different from the other two OOP programs,<br />

but you can probably still determ<strong>in</strong>e what’s happen<strong>in</strong>g.The Fraction class def<strong>in</strong>ition<br />

beg<strong>in</strong>s by declar<strong>in</strong>g the two <strong>in</strong>stance variables numerator and denom<strong>in</strong>ator as private.<br />

The Numerator and Denom<strong>in</strong>ator methods each have their getter and setter method<br />

def<strong>in</strong>ed as properties.Take a closer look at Numerator:<br />

public <strong>in</strong>t Numerator<br />

{<br />

get<br />

{<br />

return numerator;<br />

}<br />

}<br />

set<br />

{<br />

}<br />

numerator = value;<br />

The “get” code is executed when the value of the numerator is needed <strong>in</strong> an expression,<br />

such as <strong>in</strong><br />

num = myFract.Numerator;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!