wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Design of a Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Design of a "Country" class." Watch "Design of a "Country" class." New topic
Author

Design of a "Country" class.

Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 761

I've created a class to represent Countries of the world.
Here's a snippet of it.

The question is that I don't want to always have to create
a new Country class everytime - but I require something
like constant values.
e.g. Country c = Country.USA;
How do I achieve this ? Would this be too heavyweight - i.e.
instantiating all these classes up front for few hundred
countries in the world ?
Pho


Regards,

Pho
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4456
    
    6

You want to use the type-safe enum pattern discussed by Joshua Bloch in his book "Effective Java" and Craig Larman in his book "Java 2 Performance and Idioms". The Color class uses the same pattern.
You will have something like the following:
<pre>
public class Country {
public static final Country USA = new Country("United States", "US");
public static final Country CANADA = new Country("Canada", "CA");
...
private String fullName;
private String isoName;
private Country(String fullName, String isoName) {
this.fullName = fullName;
this.isoName = isoName;
}

...
}
</pre>
------------------
Junilu Lacar
Sun Certified Programmer for the Java� 2 Platform


Junilu - [How to Ask Questions] [How to Answer Questions]
 
Consider Paul's rocket mass heater.
 
subject: Design of a "Country" class.