Can we extend an enum in Java?

JavaObject Oriented ProgrammingProgramming

No, we cannot extend an enum in Java. Java enums can extend java.lang.Enum class implicitly, so enum types cannot extend another class.

Syntax

public abstract class Enum> implements Comparable, Serializable {
   // some statements
}

Enum

  • An Enum type is a special data type which is added in Java 1.5 version.
  • An Enum is used to define a collection of constants, when we need a predefined list of values which do not represent some kind of numeric or textual data, we can use an enum.
  • Enums are constants and by default, they are static and final. so the names of an enum type fields are in uppercase letters.
  • Public or protected modifiers can only be used with a top-level enum declaration, but all access modifiers can be used with nested enum declarations.

Example

Live Demo

enum Country {
   US {
      public String getCurrency() {
         return "DOLLAR";
      }
   }, RUSSIA {
      public String getCurrency() {
         return "RUBLE";
      }
   }, INDIA {
      public String getCurrency() {
         return "RUPEE";
      }
   };
   public abstract String getCurrency();
}
public class ListCurrencyTest {
   public static void main(String[] args) {
      for (Country country : Country.values()) {
         System.out.println(country.getCurrency() + " is the currecny of " + country.name());
      }
   }
}

Output

DOLLAR is the currecny of US
RUBLE is the currecny of RUSSIA
RUPEE is the currecny of INDIA
raja
Published on 28-Jun-2019 08:19:10
Advertisements