javaconstructorclass-design

How can I do temperature conversion in a class with only one field?


Temperature is measured mainly in three units: in degrees Celsius, degrees Fahrenheit and in kelvins. It’s easy to convert any of them to the two others:

Kelvin to Celsius:     C = K - 273.15
Celsius to Kelvin:     K = C + 273.15
Kelvin to Fahrenheit:  F = 9./5*(K - 273.15) + 32
Fahrenheit to Kelvin:  K = 5./9*(F - 32) + 273.15
Celsius to Fahrenheit: F = 9./5*C + 32
Fahrenheit to Celsius: C = 5./9*(F - 32)

Write class Temperature with one (and only one!) private field of type double; objects of the class describe temperature. The class has one constructor and three methods:

  • Temperature(double tm, char unit) — constructor taking temperature (as a double) and symbol of the unit used: ’C’ for Celsius, ’F’ for Fahrenheit and ’K’ for kelvins;

  • three methods („getters”) returning the temperature represented by an object,but in different units:

    public double getInC()
    public double getInF()
    public double getInK()
    

I don't really understand how to do this if we don't have an field of type char and we can't get any parameters into functions, how to solve it?

Below is what I have so far. It obviously does not fulfil the requirements yet.

public class Temperature {
    private final double tm;
    public Temperature(double tm, char unit) {
        this.tm = tm;
    }
    public double getInC(){
    }
    public double getInF(){
    }
    public double getInK(){
    }
}

Solution

  • Just create a field for the unit as well, then you have all the necessary information to do the conversion:

    public class Temperature {
        private final double tm;
        private final char unit;
    
        public Temperature(double tm, char unit) {
            this.tm = tm;
            this.unit = unit;
        }
    
        public double getInC() {
            // TODO: conversion
        }
    
        public double getInF() {
            // TODO: conversion
        }
    
        public double getInK() {
            // TODO: conversion
        }
    
        @Override
        public String toString() {
            return tm + "" + unit;
        }
    }
    

    Btw, what you have here is called a 'Value Object', and the recommendation is to add a toString() method so you can print temparatures if you want to (and later also add equals and hashcode methods to compare instances by value).

    Alternative solution if you don't want to add a field: convert the temparature given in the constructor into an internal unit (proposal: in K), and then convert to the requested temperatures from Kelvin.