Can Enum extend any class in java?

JavaObject Oriented ProgrammingProgramming

Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc.

You can define an enumeration using the keyword enum followed by the name of the enumeration as −

enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

Just like arrays, the elements/constants in an enumeration are identified using numbers starting from 0 in the above example the days are identified using numbers as shown in the following illustration −

Enumerations are similar to classes and, you can have variables, methods and constructors within them. Only concrete methods are allowed in an enumeration.

Extending a class

All enumerations internally extend a class named Enum the base class of all the language enumeration types. Since Java doesn’t support multiple inheritance you cannot extend another class with enumeration if you try to do so, a compile time error will be generated.

Example

In the following java snippet we have a class with name Sample and we have created an Enum type named Scooters and tried to extend the Sample class.

import java.util.Scanner;
class Sample {
}
enum Scooters extends Sample {
}

Output

On executing, this class generates the following compile time error.
D:\>javac EnumExample.java
EnumExample.java:5: error: '{' expected
enum Scooters extends Sample{
              ^
EnumExample.java:5: error: ',', '}', or ';' expected
enum Scooters extends Sample{
                      ^
2 errors
raja
Published on 14-Oct-2019 08:13:09
Advertisements