Enum:
- It is introduce in Java 5.
- it is a non-primitive data-type that is used to represent the set of constants such as week-days, months, directions etc.
- It is by-default static and final .
- It can be thought of as classes that have fixed set of constants.
Features:
- enum improves type safety.
- enum can be easily used in switch.
- enum can be traversed.
- enum can have fields, constructors and methods.
- enum may implement many interfaces but cannot extend any class because it internally extends Enum class.
Example:
class DemoEnum{
public enum Directions { NORTH, SOUTH, EAST, WEST}
public static void main(String[] args) {
for (Directions val : Directions.values())
System.out.println(val);
}}
Output:
NORTH
SOUTH
EAST
WEST
values() method in enum:
values() method is internally added by java-compiler to enum.
It returns an array containing all the values of the enum.
Defining enum:
The enum can be defined within or outside the class because it
is similar to a class.
Example of enum that is defined outside the class:
enum Directions { NORTH, SOUTH, EAST, WEST}
class EnumTest{
public static void main(String[] args) {
Directions val=Directions.EAST;
System.out.println(val);
}}
Output:
EAST
Example ( within the class):
class EnumTest{
enum Directions { NORTH, SOUTH, EAST, WEST;}
//semicolon(;) is optional .
public static void main(String[] args) {
Directions val=Directions.SOUTH;
//enum type is required to access SOUTH
System.out.println(val);
}}
Output:SOUTH
*********************************************************************************
Reach us At: - 0120-4029000 / 24 / 25 / 27 / 29 Mobile: 9953584548
Reach us At: - 0120-4029000 / 24 / 25 / 27 / 29 Mobile: 9953584548
Write us at: - Smruti@apextgi.com and pratap@apextgi.com
No comments:
Post a Comment