• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ENUMERATION

 
vainu siva
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
i am very new to java want know wat is enumeration....
according to me enueration creates an oblect and stores all the values in the object one by one....
can someone explain and give some examples
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15480
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There two different meanings for "enumeration" in Java.

First, there's interface java.util.Enumeration. You can use an Enumeration to walk through a collection of objects, to look at those objects one by one. Note that Enumeration is an old, legacy interface: it has been largely replaced by interface Iterator since Java 1.2.

Another meaning is enum types.
[ January 09, 2008: Message edited by: Jesper Young ]
 
Kevin Foulger
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Enums allow you to make a list of values, like an array and these can be assigned to a variable. The order the values are listed is taken into account, just as they are in an array. The values are constants and should be in capital letters.
You can treat the values in enums like objects and assign instance variables to each of those objects.

Here is an example that I�ve customized myself from an example in the SCJP Exam Study Guide (Page 63 & 64). I�ve looked into this subject and taken the code to pieces to try and understand the subject myself. I�ve also made the code a little more complicated than it is in the book. I�m currently studying for the exam.

Save this in a file called Engines.java in your java directory:

public class Engines {

enum EngineSize {
SPORTS_CAR(2.0),
SALOON(1.6),
OFF_ROADER(4.0);

EngineSize(double litres) {
this.litres = litres;
}

public double litres;

public double getLitres() {
return litres;
}
}
}


Save this in the same directory, in a file called Car.java

class Car extends Engines {
EngineSize size;

public static void main(String[] args) {

Car engine1 = new Car();
engine1.size = EngineSize.SPORTS_CAR;

Car engine2 = new Car();
engine2.size = EngineSize.SALOON;

Car engine3 = new Car();
engine3.size = EngineSize.OFF_ROADER;

System.out.println("The Sports Car's engine size is " + (engine1.size.getLitres()) + " litres");
System.out.println("The Saloon's engine size is " + (engine2.size.getLitres()) + " litres");
System.out.println("The Off Roader's engine size is " + (engine3.size.getLitres()) + " litres");

}
}


End of code

Compile both the files separately and run Car.java. You have to run this, because it contains the Main method.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic