Why is this enum declared in its own file. Is there an advantage to this? Also how would I be able to put this in one of the 2 files. I really have no clue what I am doing. Please also explain this in a simple way, since this is a textbook example, and I am fairly new to Java.
ScaleName.java
enum ScaleName {celsius, fahrenheit, kelvin, rankine};
Temperature.java
class Temperature {
private double number;
private ScaleName scale;
public Temperature() {
number = 0.0;
scale = ScaleName.fahrenheit;
}
public Temperature(double number) {
this.number = number;
scale = ScaleName.fahrenheit;
}
public Temperature(ScaleName scale) {
number = 0.0;
this.scale = scale;
}
public Temperature(double number, ScaleName scale) {
this.number = number;
this.scale = scale;
}
public void setNumber(double number) {
this.number = number;
}
public double getNumber() {
return number;
}
public void setScale(ScaleName scale) {
this.scale = scale;
}
public ScaleName getScale() {
return scale;
}
}
UseTemperature.java
class Temperature {
private double number;
private ScaleName scale;
public Temperature() {
number = 0.0;
scale = ScaleName.fahrenheit;
}
public Temperature(double number) {
this.number = number;
scale = ScaleName.fahrenheit;
}
public Temperature(ScaleName scale) {
number = 0.0;
this.scale = scale;
}
public Temperature(double number, ScaleName scale) {
this.number = number;
this.scale = scale;
}
public void setNumber(double number) {
this.number = number;
}
public double getNumber() {
return number;
}
public void setScale(ScaleName scale) {
this.scale = scale;
}
public ScaleName getScale() {
return scale;
}
}
You don’t have to declare an
enumin a separate file. You could do this:The only difference between this and making the enum a top level class is that you now need to qualify the name of the enum when you use it in a different class.
But what is going on in my example is no different to what happens if the enum was any other static nested class. (A nested enum is implicitly static, so we don’t need a
statickeyword. See JLS 8.9.)Because the code author chose to do it this way1.
Yes. It means that don’t have to qualify the
enumto use it … in some circumstances where you would have to if theenumwas nested as above.Actually, Java does allow you to put multiple top-level classes into the same source file provided that all but one of the classes is "package private". However, doing that is generally thought to be bad style, and it can be problematic for some tool chains … I have heard.
1 – If you want to know the real reason why the authors of the textbook chose to do it that way, you would need to ask them!