Java-Enumeration Super Class

Enumeration Super Class

All enumerations automatically inherit java.lang.Enum. The Enum class defines several methods such as ordinal( ), compareTo( ), equals( ) and so on, that are available for use by all enumerations. You can obtain a value that indicates an enumeration constant’s position in the list of constants. This is called its ‘ordinal value’ and it is retrieved by calling the ordinal( ) method. This method returns the ordinal value of the invoking constant. Ordinal values begin at ‘0’. For example, in the following program, in the Fruits enumeration, Apple has an ordinal value of ‘0’, Banana has an ordinal value of ‘1’, Cherry has an ordinal value of ‘2’, and so on.

You can compare the ordinal value of two contents of the same enumeration by using the compareTo( ) method. This method returns a negative integer, zero, or a positive integer as this object ordinal value less than, equal to, or greater than the specified object ordinal value. You can compare an enumeration constant with any other object by using equal( ), which overrides the equals( ) method defined by Object. Although equals( ) can compare an enumeration constant to any other object, those two objects will only be equal if they both refer to the same constant, within the same enumeration. The following program demonstrates the ordinal( )compareTo( ), and equals( ) methods.

Program

final2

Program Source

enum Fruits {
    
    Apple, Banana, Cherry, Date, Elderberry
}    
    
enum Vegetables {
    
    Carrot, Beetroot, Beans, Tomato, Onion
}

public class Javaapp {

    public static void main(String[] args) {
        
        Fruits[] fru = Fruits.values();
        for(Fruits fr : fru)
        {
            System.out.println(fr+" : "+fr.ordinal());
        }
        
        Fruits f1,f2,f3;
        f1 = Fruits.Apple;
        f2 = Fruits.Cherry;
        f3 = Fruits.Apple;
        
        if(f2.compareTo(f1) > 0)
        {
            System.out.println(f2+" comes after "+f1);
        }
        
        Vegetables v1 = Vegetables.Beetroot;
        
        if(f1.equals(v1))
        {
            System.out.println("Incorrect");
        }   
    }
}

Leave a Comment