Enums

Enum (Enumerated Types) in Java.

Syntax

//Syntax
enum Laptop{
APPLE, DELL, HTC; //Semicolon not mandatory
}

Values of an Enum and Constructor of Enums

Compiler adds a constructor to the enum. We can enter custom values for enums too. We need to create a parameterized constructor for that.

  • Example

    enum  Fruits
    {
        APPLE(“RED”), BANANA(“YELLOW”), GRAPES(“GREEN”);
    }
    

    Thus, the value of enum APPLE is not "APPLE". It is "RED" instead.

    //Example
    enum Mobile { 
    int price;
    APPLE(1200), SAMSUNG(700), HTC(400);
    Mobile(int p){ price = p} //Constructor
    }
    
  • Although, the constructor is private and hence, enums can't be initialised by new().

Methods

  • Functions values(), valueOf() and ordinal() are added by compiler/JVM to the enum

values()

  • Returns all values in the enum in form of an array.
  • Usage
Laptop.values(); 
//Output - APPLE,HTC,SAMSUNG

valueOf()

  • Returns value of given constant enum

  • Usage

    Laptops.valueOf("APPLE") 
    //APPLE
    

ordinal()

  • Returns index of an enum constant.

  • Usage

    Laptops.HTC.ordinal() //2
    

Internal Code Generated by Compiler for enums

enum Laptop{ APPLE, DELL, HTC }

All enums get converted to class. This 👆🏽 is same as writing 👇🏽

class Laptop{
public static final String APPLE = "Apple";
public static final String SAMSUNG = "Samsung";
public static final String HTC = "HTC";
}

Detailed version of the above enum code

final class Laptop extends Enum{

public static Laptop[] values{                         //values()
    return (Laptop[])$VALUES.clone();
}

public static Laptop valueOf(String s){                //valueOf()
    return (Laptop)Enum.ValueOf(Laptop, s);
}

private Laptop(String s, int i, int j){             //Constructor - is private
    super(s,i);
    value = j;
}

public static final Laptop APPLE;
public static final Laptop SAMSUNG;
public static final Laptop HTC;
private int value;
private static final $VALUES[];

static{
    APPLE = new Laptop("APPLE", 0, 1200);
    SAMSUNG = new Laptop("SAMSUNG", 1, 700);
    HTC = new Laptop("HTC", 2, 400);
    $VALUES = (new Laptop[]{
    APPLE, SAMSUNG, HTC
    });
    }
}

Enums in Switch statement

Switch statement cases can only include values which are in enum.

enum Laptop{ APPLE, DELL, SAMSUNG }
.
.
.
Laptop l = Laptop.SAMSUNG; //Creating object of enum
switch(l){
    case APPLE:
    case SAMSUNG:
    case LUDO: //Will give error.
}

Enums and Classes

  • "Inner" Enum
    • In Java, enums can be created inside a class as well.
  • Class extended by all enums
    • All enums extends a class called Enum which in turn extends Object class.
  • Inheritance in enums
    • Enums can't extend classes but can implement interfaces.
  • Difference between C++ and Java enums Data members and methods can be created inside Java enum

Difference between enums and class

  • Enum constants are public, static, final
  • Enums can't extend other classes