Enum with Customized Value in Java

Java Programming Java8Object Oriented Programming

An enum in java represents a group of named constants. It can also have custom properties and methods.

Example

Let us look at an example.

import java.lang.*;

// enum showing Mobile prices
enum Mobile {
   Samsung(400), Nokia(250),Motorola(325);

   int price;
   Mobile(int p) {
      price = p;
   }
   int showPrice() {
      return price;
   }
}

public class EnumDemo {
   public static void main(String args[]) {
      System.out.println("CellPhone List:");

      for(Mobile m : Mobile.values()) {
         System.out.println(m + " costs " + m.showPrice() + " dollars");
      }

      Mobile ret = Mobile.Motorola;
      System.out.println("MobileName = " + ret.name());
   }
}

This will produce the following result −

Output

CellPhone List:
Samsung costs 400 dollars
Nokia costs 250 dollars
Motorola costs 325 dollars
MobileName = Motorola
  • Here we've added a price as field and showPrice() as method to Enum.

  • We've assign custom values to enum using its constructor.

raja
Published on 13-Aug-2018 12:55:06
Advertisements