Lecture 5: In-class Exercise: Representing Temperature
Due: Ideally by the end of class, but not later than 24 hours after your section meeting time.
1 It’s Getting Hot
The purpose of this exercise is to give you practice with the new concepts introduced through the Durations example, such as access modifiers, static, and JavaDoc, as well as review concepts such as inheritance, equals/hashCode, and interface polymorphism.
In the starter code, you are given an interface representing a temperature value. Your task is to implement the Temperature interface in two different ways:
using a field to represent the temperature in degrees Celsius.
using a field to represent the temperature in degrees Fahrenheit.
You may work freely with other students on this exercise!
You will need two separate classes: a public classed named CelsiusTemperature, and a public class named FahrenheitTemperature. Each class will need two constructors:
CelsiusTemperature will have one constructor that takes a single
double
representing temperature in Celsius; the other constructor will take adouble
representing temperature in Fahrenheit and aboolean
whose value must be true.Conversely, FahrenheitTemperature will have one constructor that takes a single
double
representing temperature in Fahrenheit; its other constructor will take adouble
representing temperature in Celsius and aboolean
whose value must be true.
All implementations should override equals()
, hashCode()
, and toString()
. The toString() method
should return a String as follows:
"NN.N° Fahrenheit"
, namely, the temperature to one decimal place precision followed by the degree symbol
and Fahrenheit, e.g., "30.1° Fahrenheit"
, for the FahrenheitTemperature class, and similarly for
the CelsiusTemperature class but substituting "Celsius"
for "Fahrenheit"
.
You may want to copy and paste the degree symbol (°) from this Web page into IntelliJ.
You may find it useful to use String.format("%.1f")
to convert a double
to a String
with one decimal place.
The formulas for converting between Celsius and Fahrenheit are as follows:
2 Testing
We have supplied you with some basic JUnit tests as part of the starter code. Use these to verify that your implementation is correct, and write additional tests of your own.
3 Notes to Keep in Mind
Avoid duplicating code as much as possible. You will likely want to use an abstract superclass. Consider also using non-public methods as means of creating reusable pieces of functionality.
Be sure to use access modifiers,
private
, default (no keyword),protected
, andpublic
appropriately.Include JavaDoc for your classes and constructors as appropriate. You do not need to repeat JavaDoc already existing in a superclass or interface when you override a method. This is true for the course in general.
4 To Turn In
Submit your zip containing only your src and test directories to In-class Exercise 1 on the handin server. There is no self-evalulation for this exercise.