Enum and Construction, Enum Inheritance & Enum Methods in Java
In the previous blog, I have explained the Basic Concept of Enumeration with Example.
Enum and Constructor:-
Constructor in Enum is Executed separately for each enum constant at the time of enum class loading.
We can't invoke Constructor directly because we can't create the enum object explicitly.
Enum and Methods:-
Enum can contain the Concrete method and Abstract method. If an abstract method, then each instance of the enum class must implement it.
Example:-
enum color
{
red, green, blue;
}
private color
{
System.out.println("Constructor called for :"+ this.toString());
}
public class test
{
public static void main(String args[])
{
color c= color.red;
System.out.println(c1);
}
Another Example of enum with Constructor and instance variable and methods:-
enum student
{
harry(20), robert(25), sam(15), veer(18);
private int age;
int getage
{
return age;
}
public student(int age)
{
this.age = age;
}
class test
{
public static void main(String args[])
{
student s;
System.out.println("age of harry is :"+ student.harry.getage()+"years");
}
}
Enum and Inheritance:-
All Enums implicitly extend java.lang.enum class. In java, a class can extend only one parent. So an enum can't extend anything else.
Enum can implement many interfaces.
toString() method is overridden in java.lang.enum class. Which returns enum constant name.
values(), valueOf(), and ordinal() methods:-
These methods are present in java.lang.enum class.
values() method can be used to return all values inside the enum class.
Order is important in enums, by using the ordinal() method each enum constant index can be found, just like an array index.
valueOf() methods return the enum constant of the specified string value if exists.
Example:-
enum color
{
red, green, blue;
}
public class test
{
public static void main(String args[])
{
color ar[] = color.values();
for(color col : ar)
{
System.out.println(col + "at index" + col.ordinal());
}
System.out.println(Color.valueOf("red"));
}
}
Points to remember about enumeration:-
Enumerations are of class type and have all the capabilities that a java class has.
Enumerations can have Constructors, instance variables and methods can even implement interfaces.
Enumerations are not instantiated using the new keyword.
All Enumerations by default inherits java.lang.enum class.
0 Comments