Enumerations was added to Java language in JDK5.
Enumeration means a list of named constant.
In Java, enumeration defines a class type.
An Enumeration can have constructors, methods and instance
variables.
It is created using enum keyword.
Each enumeration constant is public, static and final by
default.
Even though enumeration defines a class type and have
constructors, you do not instantiate an enum using new.
Enumeration variables are used and declared in much a same way
as you do a primitive variable.
How to Define and Use an Enumeration
An enumeration can be defined simply by creating a list of
enum variable.
Let us take an example for list of Subject variable,
with different subjects in the list.
enum Subject //Enumeration defined
{
Java, Cpp, C, Dbms
}
enum WeekDays
{ sun, mon, tues, wed, thurs, fri, sat }
class Test
{
public static void main(String args[])
{
WeekDays wk;
wk = WeekDays.sun;
System.out.println("Today is "+wk);
}
}
program2
enum Student
{
John(11), Bella(10), Sam(13), Viraaj(9);
private int age; //age of students
int getage { return age; }
public Student(int age)
{
this.age= age;
}
}
class EnumDemo
{
public static void main( String args[] )
{
Student S;
System.out.println("Age of Viraaj is " +Student.Viraaj.getage()+ "years");
}
}
Enumeration means a list of named constant.
In Java, enumeration defines a class type.
An Enumeration can have constructors, methods and instance
variables.
It is created using enum keyword.
Each enumeration constant is public, static and final by
default.
Even though enumeration defines a class type and have
constructors, you do not instantiate an enum using new.
Enumeration variables are used and declared in much a same way
as you do a primitive variable.
How to Define and Use an Enumeration
An enumeration can be defined simply by creating a list of
enum variable.
Let us take an example for list of Subject variable,
with different subjects in the list.
enum Subject //Enumeration defined
{
Java, Cpp, C, Dbms
}
enum WeekDays
{ sun, mon, tues, wed, thurs, fri, sat }
class Test
{
public static void main(String args[])
{
WeekDays wk;
wk = WeekDays.sun;
System.out.println("Today is "+wk);
}
}
program2
enum Student
{
John(11), Bella(10), Sam(13), Viraaj(9);
private int age; //age of students
int getage { return age; }
public Student(int age)
{
this.age= age;
}
}
class EnumDemo
{
public static void main( String args[] )
{
Student S;
System.out.println("Age of Viraaj is " +Student.Viraaj.getage()+ "years");
}
}
No comments:
Post a Comment