I am doing a college exercise and would like to know how to improve the execution of the idea. The idea is to create a program that converts temperature measurements.
Main.java
package app.cnv;
public class Main {
public static void main(String[] args) {
Celsius celsius = new Celsius(37);
System.out.println(celsius.convert(new Fahrenheit()));
Fahrenheit fahrenheit = new Fahrenheit(98.6);
try {
System.out.println(fahrenheit.convert(new Celsius()));
} catch (AbsoluteZeroException e) {
System.out.println(e.getMessage());
}
}
}
Temperature.java
package app.cnv;
public abstract class Temperature {
public abstract double convert(Temperature to) throws AbsoluteZeroException;
}
Celsius.java
package app.cnv;
public class Celsius extends Temperature {
double celsius;
Celsius() {
}
Celsius(double celsius) {
this.celsius = celsius;
}
@Override
public double convert(Temperature to) {
if (to instanceof Fahrenheit) {
return (celsius * 9) / 5 + 32;
}
return celsius;
}
}
Fahrenheit.java
package app.cnv;
public class Fahrenheit extends Temperature {
double fahrenheit;
Fahrenheit() {
}
Fahrenheit(double fahrenheit) {
this.fahrenheit = fahrenheit;
}
@Override
public double convert(Temperature to) throws AbsoluteZeroException {
if (to instanceof Celsius) {
if (fahrenheit < -459.67) {
throw new AbsoluteZeroException("The temperature cannot be less than absolute zero.");
} else {
return ((fahrenheit - 32) * 5) / 9;
}
}
return fahrenheit;
}
}
AbsoluteZeroException.java
package app.cnv;
public class AbsoluteZeroException extends Exception {
public AbsoluteZeroException(String err) {
super(err);
}
}