Inheritance on an Enum in Java

In Java, an enum
(short form for enumeration) is a data type with a fixed constant value set. We use the enum
keyword to declare the enumeration data type.
It is a common practice to represent enum
values in uppercase. In Java, all the enum
classes are final
by default.
So, we cannot inherit or derive different classes from it.
Use enum
s in Java
enum Seasons
{
SUMMER, WINTER, AUTUMN, SPRING
}
class Main
{
public static void main(String[] args)
{
System.out.println(Seasons.SUMMER);
System.out.println(Seasons.WINTER);
System.out.println(Seasons.AUTUMN);
System.out.println(Seasons.SPRING);
}
}
Output:
SUMMER
WINTER
AUTUMN
SPRING
The above code displays the functionality of an enum
data type. The use of enum
s can make any code more explicit and less error-prone.
Enum
s are widely used in menu-driven programs or when we know all possible values at compile time.
Java enum
Inheritance
enum Seasons
{
SUMMER, WINTER, AUTUMN, SPRING
}
class Main
{
class Weather extends Seasons
{
public static void main(String[] args)
{
// statements
}
}
}
Output:
Main.java:8: error: cannot inherit from final Seasons
class Weather extends Seasons {
^
Main.java:8: error: enum types are not extensible
class Weather extends Seasons {
^
The above code produces an error because an enum
class cannot be used to derive another functional class.
Use an enum
to Implement an Interface
interface Weather {
public void display();
}
enum Seasons implements Weather
{
SUMMER, WINTER, AUTUMN, SPRING;
public void display()
{
System.out.println("The season is " + this);
}
}
class Main
{
public static void main(String[] args)
{
Seasons.SUMMER.display();
}
}
Output:
The season is SUMMER
In the above code, we are using an enum
class, Seasons
, to implement the Weather
interface. Since we can use an enum
class to implement an interface, we have written the abstract method display()
inside the enum
class.
Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.
LinkedIn