In case of enum
1.
All the constant variable are by default “public
static final”, no need to declare explicitly.
2.
All the constant variable are by default of same
enum type, no need to provide any data type.
3.
All the constant variables are by default named
constants, if we access constant variable then we are able to get name of the
constant variables not values of the constant variable.
Syntax :-
[Access_Modifier] enum Name
{
---list
of constant variables---
}
Ex code :-
enum User_Status
{
AVAILABLE,
BUSY, IDLE;
}
class Test
{
public
static void main(String[] args)
{
System.out.println(User_Status.AVAILABLE);
System.out.println(User_Status.BUSY);
System.out.println(User_Status.IDLE);
}
}
On Command prompt :-
javap User_Status
if we compile the above enum then
compiler will translate enum into the final classs like below.
Compiled from
"Test.java"
final class User_Status extends
java.lang.Enum<User_Status>{
public static final User_Status
AVAILABLE;
public static final User_Status
BUSY;
public static final User_Status
IDLE;
public static User_Status[]
values();
public static User_Status
valueOf(java.lang.String);
static {};
In java applications, we are able
to use enums like classes, where we are able to declare normal variables,
methods, constructors,…. As per the requirement.
Ex code :-
enum Apple
{
A(500),B(300),C(100);
int
price;
Apple(int
price)
{
this.price=price;
}
public
int getPrice()
{
return
price;
}
}
class Test
{
public
static void main(String[] args)
{
System.out.println("A
Grade Apple:"+Apple.A.getPrice());
System.out.println("B
Grade Apple:"+Apple.B.getPrice());
System.out.println("C
Grade Apple:"+Apple.C.getPrice());
}
}
Output:-
A Grade Apple:500
B Grade Apple:300
C Grade Apple:100
If the compile the above enum then
compiler will translate the above enum into final class like below
Ex code:-
final class Apple extends
java.lang.Enum
{
public
static final Apple A=new Apple(500);
public
static final Apple B=new Apple(300);
public
static final Apple C=new Apple(100);
int
price;
Apple(int
price)
{
this.price=price;
}
public
int getPrice()
{
return
price;
}
}
No comments:
Post a Comment