TestEnum.java
| Title: | C++ Style Enumerations for Java
|
| Copyright: | Copyright (c) 2000
|
| Author: | Bob Byron,
|
| Company: | RAD Systems, Inc.
|
| Revised By: | Roseanne Zhang
|
class TestEnum {
void travel(Transport transport, Location location) {
System.out.println("You took a " + transport + " to " + location);
// All the enum benifits of C++ can be achieved here
// with stronger type checking.
// Encapsulisation is good. outside world only need to know the names
// disadvantage: switch statwment is not allowed here
if (transport == Transport.STEAMBOAT)
; // do someing with steam boat
else if (transport == Transport.JETPLANE)
; // do someing with jet plane
else if (transport == Transport.RACECAR)
; // do someing with race car
else if (transport == Transport.FLYINGSAUCER)
; // do someing with flying saucer
}
public static void main(String[] args) {
TestEnum testEnum = new TestEnum();
testEnum.travel(Transport.STEAMBOAT, Location.NEWORLEANS);
testEnum.travel(Transport.JETPLANE, Location.LOSANGELES);
testEnum.travel(Transport.RACECAR, Location.MEMORYLANE);
testEnum.travel(Transport.FLYINGSAUCER,Location.ROSWELLNM);
}
}
// Using final to avoid inheritance and overriding
// declare it public and put it into a seperated file
// if it is used in more packages
final class Location {
private String sLocation;
// private constructor to avoid outside instantiation
private Location(String sLocation) {
this.sLocation = sLocation;
}
// You can add more methods here to make the class normal
public String toString() {return sLocation;}
// more methods here.......
// All discrete values allowed listed here, no interger euivalent exists
// Strong type checking guaranteed
public static Location ROSWELLNM = new Location("Roswell, New Mexico");
public static Location MEMORYLANE = new Location("Memory Lane");
public static Location NEWORLEANS = new Location("New Orleans");
public static Location LOSANGELES = new Location("Los Angeles");
}
final class Transport {
private String sTransport;
private Transport(String sTransport) {
this.sTransport = sTransport;
}
public String toString() {return sTransport;}
public static Transport JETPLANE = new Transport("jet plane");
public static Transport STEAMBOAT = new Transport("steam boat");
public static Transport RACECAR = new Transport("race car");
public static Transport FLYINGSAUCER = new Transport("flying saucer");
}
Discussion:
When we need limited number discrete values, we use enum in c++. There is no enum in java. Using the mechanism introduced in this
module, you will hava stronger than c++ type checking "enum" in java, and all the other common object's behavior
if it is desired.
Some Disadvantage:
switch statement cannot be used here without complicated code.
Hard coded cases.
Contruct too many objects.
Last updated 03-25-2002 by webmaster