Monday, 25 April 2016

Are Java Enums are Comparable & Serializable automatically ?


Are Java Enums are Comparable & Serializable automatically ?

Yes, Enums are automatically Comparable as well as Serializable.
There is no need to explicitly add the "implements Comparable" or "implements Serializable".

Following program will check if the enum is instance of Comparable and Serializable :

enum Day {
       SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}

public class EnumTest {
       public static void main(String[] args) {
              Day day1 = Day.MONDAY;
              boolean isComparable = (day1 instanceof Comparable);
              boolean isSerializable = (day1 instanceof Serializable);
              System.out.println(“Comparable :” + isComparable);
              System.out.println(“Serializable :” + isSerializable);
       }
}

Output
Comparable : true
Serializable : true

No comments:

Post a Comment

Note: only a member of this blog may post a comment.