A Problem Solved: Designing a Class of Temperatures

In this lesson, we will design a class to represent temperatures and provide methods for conversions among different possible temperature scales.

Problem statement

Temperatures can be represented in degrees Fahrenheit, degrees Celsius, or in kelvins. You can think of a kelvin as one “degree” on the Kelvin scale; it just isn’t called a degree. Scientists use the letters F, C, and K to represent the scale of a given temperature. For example, water freezes at 32 degrees Fahrenheit (32°F), 0 degrees Celsius (0°C), and 273.15 kelvins (273.15 K). Define a class Temperature that represents temperatures. An object in this class should be able to convert from one scale to another and must keep track of its present scale.

Designing the class

We need to think about the class’s data fields, constructors, and methods.

The data fields

A Temperature object should have data to represent its temperature value and its scale. Thus, the class definition needs to define data fields for this data. The temperature value can have a numeric data type, such as int or double, according to the precision we want for this value. The temperature scale can be a code, such as an integer or a character, or we could give it an enumerated data type. Let’s choose the latter data type, and define the following enumeration:

public enum Scale {C, F, K}

Any constructors and methods that we choose can affect our class’s data fields according to any arguments they receive when invoked.

Get hands-on with 1200+ tech skills courses.