What is a reasonable implementation of this uml graph in java?
where Enumeration,Eiche,Buche,Esche is german and means enum, oak, beech, ash. My attempt was the following
public class Material{
public static enum material{
oak, beech, ash
}
public int[] materialCost ={1,2,3};
}
The problem ist that somewhere in my homework-excercise I find Table(Material.oak)
so I know my attempt must be wrong. Can anyone help?
CodePudding user response:
In short
public enum Material {
Eiche,Buche,Esche;
public int materialCost; // public access is not great, but that's the model
}
Detailed justification based on the UML diagram
The UML keyword «enumeration»
corresponds in Java to an enum
.
UML enumeration literals such as Eiche
, Buche
, Esche
, are generally not underlined and are placed in a separate compartment with only literals. This compartment should be graphically place below the operations, which are themselves sperated from the attributes. Your graphical notation does not respect this usage, so a closer look is needed to avoid confusion. Underlined elements in an UML class are static elements, but in the specific case of enumeration, the underline means an "instance specification" (sorry for the UML jargon) i.e. some constant enum values.
materialCost
is not underlined. It's therefore a normal, public attribute. Some languages do not allow additional attributes and operations for an enumeration, but UML does. And fortunately Java as well. We do not know the type of this attribute, so you could chose what is relevant in the implementation; int
seems ok. materialCost
should not be an array: an array would require a multiplicity greater than 1 in UML since you could have more than one element. In the diagram there is no explicit multiplicity which means (according to the UML specs) a multiplicity of exactly 1.
Last but not least, the materialCost
could perfectly be modified at any time according to the UML model, since it is not followed by {readOnly}
. It's not an operation either since ()
is missing
Additional remarks
In UML an enum is a value type: if two instances have the same values they are considered as identical.
In Java it's a little more tricky, because of the difference between ==
and .equals()
and the special guarantees about ==
when comparing to enum literals and in absence of additional fields. SOme prudence seems advisable for this kind of hybrid enums.
CodePudding user response:
You can actually define attributes on Enum types pretty similarly to normal classes: Oracle docs
So in your example you could do something like
public enum Material {
EICHE(1),
BUCHE(2);
private final int cost;
Material(int cost) {
this.cost = cost;
}
int cost() {
return this.cost;
}
}
...
Material oak = Material.EICHE;
System.out.println("One unit of Eiche costs " oak.cost());