A Problem Solved: Defining the Class Temperature
In this lesson, we will continue our discussion of the class Temperature by examining the details of its definition.
The enumeration
As we mentioned in the previous lesson, we want to use an enumeration to represent the scale of the temperature. We saw then that the client of the class Temperature
uses this enumeration.
However, we also want Temperature
itself to use it. If we define an enumeration within a class, it is private and can be used only within that class. Here we want the client and Temperature
to use the enumeration. As we know from the previous chapter, an enumeration is actually a class. Thus, we made the enumeration public and defined it within its own file, just as we do with other classes that we write.
Let’s recall the definition of the enumeration Scale
from the previous lesson and store it in the file Scale.java
:
public enum Scale {C, F, K}
The data fields
Our class design specifies each Temperature
object to record the value and scale of the temperature that it represents. Let’s decide to make the value of the temperature a real number. We already decided that its scale will have the enumerated data type Scale
. Thus, the class Temperature
can define the following data fields:
private double value;
private Scale scale;
The constructor will give these fields values according to the arguments it receives when it is invoked.
The conversion methods
Each one of the conversion methods must convert the temperature from its present scale to the desired scale. For example, the method convertToFahrenheit
must be able to ...