This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 4446
    
    5

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]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Design of a "Country" class.
 
Similar Threads
jaxb be converting bean to xml
How to retain value in struts 2 using <s:select></s:select> tag
Populating dropdown menu based on another
creating an array
question about locale