Programming in C

(Barry) #1

424 Chapter 19 Object-Oriented Programming


The “set” code is executed when a value is assigned to the method, as in
myFract.Numerator = 1;
The actual value that is assigned gets stored in the variable valuewhen the method gets
called. Note that parentheses do not follow the setter and getter methods here.
Naturally, you can define methods that optionally take arguments, or setter methods
that take multiple arguments. For example, this C# method invocation might be used to
set the value of a fraction to 2/5 with a single call:
myFract.setNumAndDen (2, 5)
Returning to Program 19.4, the statement
Fraction myFract = new Fraction();
is used to create a new instance from the Fractionclass and assign the result to the
Fractionvariable myFract.The Fractionis then set to 1/3 using the Fraction’s set-
ters.
The print method is invoked next on myFractto display the value of the fraction.
Inside the printmethod, the WriteLinemethod from the Consoleclass is used to dis-
play output. Similar to printf’s %notation,{0}specifies in the string where the first
value is be substituted,{1}where the second value is to be displayed, and so on. Unlike
the printfroutine, you don’t need to worry here about the types being displayed.
As with the C++ example, the getter methods for the C# Fractionclass were not
exercised here.They were included for illustrative purposes.
This concludes this brief introduction to object-oriented programming. Hopefully,
this chapter has given you a better idea about what object-oriented programming is all
about and how programming in an OOP language differs from a language such as C.
You have seen how you can write a simple program in one of three OOP languages to
work with objects that represent fractions. If you were serious about working with frac-
tions in your programs, you would probably extend your class definition to support
operations such as addition, subtraction, multiplication, division, inversion, and reduction
of fractions, for example.This would be a relatively straightforward task for you to do.
To continue your studies further, get a good tutorial on a particular OOP language,
such as one listed in Appendix E.
Free download pdf