Suppose there is an ENUM
enum Operations {
ADD,
SUBTRACT,
MULTIPLY
}
I want to use this enum to add two numbers(say 5 and 3) and get the output as 8 or I want to use this enum to subtract two numbers(say 9 and 3) and get the output as 6
Question:
In Java (from 1.5), enums are represented using enum data type. Java enums are more powerful than C/C++ enums. In Java, we can also add variables, methods and constructors to it. The main objective of enum is to define our own data types (Enumerated Data Types).
Last Updated : 21 Dec, 2018. Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. enum State {Working = 1, Failed = 0}; The keyword ‘enum’ is used to declare new enumeration types in C and C++.
Interesting facts about initialization of enum. 1. Two enum names can have same value. For example, in the following C program both ‘Failed’ and ‘Freezed’ have same value 0.
The value assigned to enum names must be some integeral constant, i.e., the value must be in range from minimum possible integer value to maximum possible integer value. 5. All enum constants must be unique in their scope. For example, the following program fails in compilation.
enum
s can have abstract methods, and each member can implement it differently.
enum Operations {
ADD {
public double apply(double a, double b) { return a + b; }
},
SUBTRACT {
public double apply(double a, double b) { return a - b; }
},
MULTIPLY {
public double apply(double a, double b) { return a * b; }
},
;
public abstract double apply(double a, double b);
}
will allow you to do
Operations op = ...;
double result = op.apply(3, 5);
How about using JAVA 8 features:
enum Operation implements DoubleBinaryOperator {
PLUS ("+", (l, r) -> l + r),
MINUS ("-", (l, r) -> l - r),
MULTIPLY("*", (l, r) -> l * r),
DIVIDE ("/", (l, r) -> l / r);
private final String symbol;
private final DoubleBinaryOperator binaryOperator;
private Operation(final String symbol, final DoubleBinaryOperator binaryOperator) {
this.symbol = symbol;
this.binaryOperator = binaryOperator;
}
public String getSymbol() {
return symbol;
}
@Override
public double applyAsDouble(final double left, final double right) {
return binaryOperator.applyAsDouble(left, right);
}
}
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