jQuery in Action, 3rd edition
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

Design of a "Country" class.

Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 782

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 ?


Junilu Lacar

Joined: Feb 26, 2001
Posts: 6529

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:
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;

Junilu Lacar
Sun Certified Programmer for the Java� 2 Platform

Junilu - [How to Ask Questions] [How to Answer Questions]
I agree. Here's the link: http://aspose.com/file-tools
subject: Design of a "Country" class.
It's not a secret anymore!