Header Ads

How Inheritance Concept Works For Java Enum??

In my previous post (http://www.mydigitalvoice.in/2013/05/enum-concept-simplified-in-java.html) I have told how compiler will treat enum.
It will treat enum as a class.
enum Month  
{  
JAN,FEB,MAR;  
//note semicolon(;) is optional here  
}  
will be transferred by the compiler as..
Class Month  
{  
//for JAN  
public static final Month JAN=new Month();  
//similarly for FEB and MAR  
public static final Month FEB=new Month();  
public static final Month MAR=new Month();  
}  

Since the underlying concept is class, the very next question arises as can Inheritance concept works for enum? Let us see few concepts..

  • Every enum is direct child of java.lang.Enum class in java, So enum can't extend any other enum
  • Every enum is always final implicitly hence we can't create child enum
With the above statements we can conclude that inheritance concept is not applicable for explicitly.Hence we can't use extends keyword for enums.
enum x
{}
enum y extends x{}
output: Compile time error
enum x extends java.lan.Enum
{}
output: Compile time error
Class x
{}
enum y extends x{}
output: Compile time error
enum x
{}
Class y extends x{}
output: Compile time error
Can not inherit from final (enum) or enum types are not extensible

However an enum can implement any no of interfaces simultaneously.
interface x
{}
enum y implements x{}
Valid deceleration.
Powered by Blogger.