Java Reference
In-Depth Information
demarcation is removed. The focus of your cursor is left within the body
of the new method. Delete the default body, and you'll give the service
some functionality.
Let's make the service return a fixed rate of 1
US
dollar to 1.50 Canadian
dollars for now. This means that if someone requests a
USD
to
CDN
con-
version, the rate returned will be 1.5; if someone requests a
CDN
to
USD
conversion, the rate will be the inverse: 2/3, or 0.66. A fixed value will
make the converter easy to test. You'll store that value in a private vari-
able called
rate
and initialize that value in the class constructor. Move
your cursor inside the class definition and add the line
private double
rate;
to add the field.
4
Select the
Code | Generate
menu option to bring up the pop-up
(
Alt+Insert
). Why write when you can generate?
5
Choose the
Constructor
option, and then click the
Select None
button,
because the constructor won't take arguments.
6
Inside the constructor, set the rate to be 1.5 with the line
rate = 1.5;
.
Choose the
Code | Generate
option again to generate getters and set-
ters for the
rate
variable.
7
We haven't discussed what to do if you're passed currency acronyms in
the implemented
getCurrentRate()
method. There's a lot more error-
checking you could implement here. For now, you'll just return a zero,
but we'll revisit that implementation in a short while. For now, edit your
service class to look like listing 3.2.
8
One more alteration you can make is to have the currency exchange ser-
vice factory from Chapter 2 return an instance of this fixed rate factory.
Open the
CurrencyExchangeServiceFactory
class—possibly with the
Go
To | Class
command (
Ctrl+N
)—and change the line inside the
get-
Service()
method to read as follows:
9
return new FixedRateCurrencyExchangeService();
If you notice errors or intention actions as you work, feel free to stop and
investigate them. Don't forget to try out some of the features outlined in
this chapter, such as the following:
NOTE
Code completion
—Type
fromCurrency.
and then press
Ctrl+ Space
for basic completion, and select
equals()
from the list of options.
■