Answer the question
In order to leave comments, you need to log in
Is it possible to do some calculations in the enum?
Hello, I have a purely school question.
Is it possible to do some calculations in the enumeration, or is it an antipattern?
For example, the Calculator program.
I create a Calculator class.
B enumeration Operation - operations +-*/
If I make the method
count(double firstNumber, double secondNumber) in the enumeration?
And I will call it from the Calculator.
Answer the question
In order to leave comments, you need to log in
An enum is syntactic sugar on top of a regular class, so there are no technical restrictions on stuffing logic into it. In addition, it is also appropriate from an architectural point of view. Joshua Bloch, in article 30 of the sixth chapter of his textbook "Effective Java", gives several such examples. One of them is very similar to yours:
enum Operation {
PLUS("+") {
double apply(double x, double y) { return x + y; }
},
MINUS("-") {
double apply(double x, double y) { return x - y; }
},
TIMES("*") {
double apply(double x, double y) { return x * y; }
},
DIVIDE("/") {
double apply(double x, double y) { return x / y; }
};
private final String symbol;
Operation(String symbol) {
this.symbol = symbol;
}
@Overrided
public String toString() {
return symbol;
}
abstract double apply(double x, double y);
}
public class Example {
public static void main(String[] args) {
double x = Double.parseDouble(args[0]);
double y = Double.parseDouble(args[1]);
for (Operation op : Operation.values())
System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x, y));
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question