Java Enum Behaviour

In this chapter you will learn:

  1. Java Enum Behaviour
  2. Assign a different behavior to each constant

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:

  1. What is an exception
  2. Keywords
  3. What is the syntax for try catch finally statement
  4. How to use try and catch
  5. Example - handles an exception and move on
Home »
  Java Tutorial »
    Java Langauge »
      Java Enum
Java Enum type
Java Enum values() / valueOf() Methods
Java Enum as Class
Java Enum Inherit Enum
Java Enum compareTo
Java Enum equals
Java Enum Behaviour