please my question are two and very simple
misinterpret enum as is
this idea missing some important abstraction in my code
code example, where oprt.calc(x, y)
isn't compilable, with warning cannot find symbol
public enum Operation {
PLUS {
public double calc(double x, double y) {
return x + y;
}
},
MINUS {
public double calc(double x, double y) {
return x - y;
}
},
MULTILPLE {
public double calc(double x, double y) {
return x * y;
}
},
DIVIDED_BY {
public double calc(double x, double y) {
return x / y;
}
};
public static void main(String args[]) {
double x = 15.25;
double y = 24.50;
for (Operation oprt : Operation.values()) {
System.out.println(x + " " + oprt + " "
+ y + " = " + oprt.calc(x, y));
}
}
}
valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type.
As it is said above,Enum are immutable in the Java, So the hashcode generated for a Enum is a perfect key for a Hash collection,just as the String are perfect keys. The enum declaration is a special kind of class declaration. An enum type has public, self-typed members for each of the named enum constants.
The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.
Enum, which is also known as enumeration, is a user-defined data type that enables you to create a new data type that has a fixed range of possible values, and the variable can select one value from the set of values.
What you miss is abstract declaration of calc() method:
enum Operation {
PLUS {
public double calc(double x, double y) {
return x + y;
}
},
MINUS {
public double calc(double x, double y) {
return x - y;
}
},
MULTILPLE {
public double calc(double x, double y) {
return x * y;
}
},
DIVIDED_BY {
public double calc(double x, double y) {
return x / y;
}
};
**public abstract double calc(double x, double y);**
public static void main(String args[]) {
double x = 15.25;
double y = 24.50;
for (Operation oprt : Operation.values()) {
System.out.println(x + " " + oprt + " "
+ y + " = " + oprt.calc(x, y));
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With