I have to implement a method (Factory-method) called createFromCelsius
, where i can create new Objects with the specific Temperature unit (celsius, kelvin…). I also created methods to convert the code from one unit to another. The problem is i dont know how i can connect the covert-methods to the createFromCelsius
method. I tried to make all my methods and variables abstact
so that i can call them. The Question: How can i implement the convert-methods in the create-methods?
Here’s my code:
public class Temperatur { private final float temp; /** * Static variable for kelvin */ public static final float KELVIN_OFFSET = 273.15f; private Temperatur(float temp) { this.temp = temp; } private static Temperatur createfromCelsius(final float temp) { return createfromCelsius(temp); } private static Temperatur createfromFahrenheit(final float temp) { return createfromFahrenheit(temp); } private static Temperatur createfromKelvin(final float temp) { return createfromKelvin(temp); } /** * converts celsius into kelvin * * @return */ public float celsiusToKelvin() { return (temp + KELVIN_OFFSET); } /** * converts celsius into fahrenheit * * @return */ public float celsiusToFahrenheit() { return (temp * (9f / 5f) + 32f); } /** * converts kelvin into celsius * * @return */ public float kelvinToCelsius() { return (temp - KELVIN_OFFSET); } /** * converts kelvin into fahrenheit * * @return */ public float kelvinToFahrenheit() { return (((temp - KELVIN_OFFSET) * (9f / 5f)) + 32f); } /** * converts fahrenheit into celsius * * @return */ public float fahrenheitToCelsius() { return (((temp - 32f) * (5f / 9f))); } /** * converts fahrenheit into kelvin * * @return */ public float fahrenheitToKelvin() { return ((temp + 459.67f) * (5f / 9f)); } }
Advertisement
Answer
As mentioned, abstract
doesn’t do what you want
A factory would work like this
private static Temperatur createfromCelsius(final float temp) { return new Temperatur(temp); }
However, you should define what base unit of measurement your temp field in the class should be rather than passing through the factory parameter. For example, if you want to convert everything to Kelvin, that’d look like
private static Temperatur createfromCelsius(final float temp) { Temperatur t = new Temperatur(temp); // or do the math directly here t.temp = t.celsiusToKelvin(); return t; }
Then you’d only need public getter methods for one way conversions from Kelvin