HI peeps,
I have a question about the following program:
TempScale.java:
public enum TempScale {
CELSIUS, FAHRENHEIT, KELVIN, RANKINE,
NEWTON, DELISLE, R�AUMUR, R�MER, LEIDEN
};
Temperature.java
public class Temperature {
private double number;
private TempScale scale;
public Temperature() {
number = 0.0;
scale = TempScale.FAHRENHEIT;
}
public Temperature(double number) {
this.number = number;
scale = TempScale.FAHRENHEIT;
}
public Temperature(TempScale scale) {
number = 0.0;
this.scale = scale;
}
public Temperature(double number, TempScale scale) {
this.number = number;
this.scale = scale;
}
public void setNumber(double number) {
this.number = number;
}
public double getNumber() {
return number;
}
public void setScale(TempScale scale) {
this.scale = scale;
}
public TempScale getScale() {
return scale;
}
}
UseTemperature.java
import static java.lang.System.out;
class UseTemperature {
public static void main(String args[]) {
final String format = "%5.2f degrees %s\n";
Temperature temp = new Temperature();
temp.setNumber(70.0);
temp.setScale(TempScale.FAHRENHEIT);
out.printf(format, temp.getNumber(),
temp.getScale());
temp = new Temperature(32.0);
out.printf(format, temp.getNumber(),
temp.getScale());
temp = new Temperature(TempScale.CELSIUS);
out.printf(format, temp.getNumber(),
temp.getScale());
temp = new Temperature(2.73, TempScale.KELVIN);
out.printf(format, temp.getNumber(),
temp.getScale());
}
}
Now, the way the program works is fairly clear, but what I don't understand is why they use constructors...what's the point of that? My understanding is that everytime a new object is called, then the "equivalent" constructor is called and the values assigned to the variables: like when this statement executes Temperature temp = new Temperature();
then this constructor gets called
public Temperature(){
number = 0.0;
scale = TempScale.FAHRENHEIT;
}
So as mentioned, what's the point of calling the constructor? The variables values can be set using the setters, so what happens if we get rid of them? Can anybody kindly (and clearly) explain the point of having them please?
thanks