Java Enum Behaviour
In this chapter you will learn:
Description
We can define enum value with different behaviours by implementing abstract method differently.
Example
We can assign different value for each constant in an enum
.
enum Converter {/*from ww w . j a va 2s . com*/
DollarToEuro("Dollar to Euro") {
@Override
double convert(double value) {
return value * 0.9;
}
},
DollarToPound("Dollar to Pound") {
@Override
double convert(double value) {
return value * .8;
}
};
Converter(String desc) {
this.desc = desc;
}
private String desc;
@Override
public String toString() {
return desc;
}
abstract double convert(double value);
}
public class Main{
public static void main(String[] args) {
System.out.println(Converter.DollarToEuro + " = " + Converter.DollarToEuro.convert(100.0));
System.out.println(Converter.DollarToPound + " = " + Converter.DollarToPound.convert(98.6));
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- What is an exception
- Keywords
- What is the syntax for try catch finally statement
- How to use try and catch
- Example - handles an exception and move on