Home > Articles > Programming > Java

Static, Final, and Enumerated Types in Java

Enumerated types help you to specify what values can be assigned to a variable, making your Java code more readable. This chapter will show you how to use enumerated types to clean up your code in JDK 1.5.
This chapter is from the book

This chapter is from the book

  • What Field Modifier static Means

  • What Field Modifier final Means

  • Why Enumerate a Type?

  • Statements Updated for Enumerations

  • More Complicated Enumerated Types

  • Some Light Relief—The Haunted Zen Garden of Apple

Enumerated types were brought into Java with the JDK 1.5 release. They are not a new idea in programming, and lots of other languages already have them. The word "enumerate" means "to specify individually". An enumerated type is one where we specify individually (as words) all the legal values for that type.

For a type that represents t-shirt sizes, the values might be small, medium, large, extraLarge. For a bread flavors type, some values could be wholewheat, ninegrain, rye, french, sourdough. A DaysOfTheWeek enumerated type will have legal values of Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday.

The values have to be identifiers. In the USA, ladies' dress sizes are 2, 4, 6, 8, 10, 12, 14, 16. As a Java enumeration, that would have to be represented in words as two, four, or any other characters that form an identifier, such as size2, size4 etc.

When you declare a variable that belongs to an enumerated type, it can only hold one value at a time, and it can't hold values from some other type. A t-shirt size enum variable can't hold "large" and "small" simultaneously, just as an int can't hold two values simultaneously. You can't assign "Monday" to a t-shirt size variable. Though enumerated types aren't essential, they make some kinds of code more readable.

enum is a new keyword

Although JDK 1.5 introduced extensive language changes, "enum" is the only new keyword brought into the language. If any of your existing programs use the word "enum" as an identifier, you will have to change them before you can use JDK.5 features.

The identifier enum might well be in programs that use the older class java.util.Enumeration. That class has nothing to do with the enum type, but is a way of iterating through all the objects in a data structure class. Many people (including me) declared variables such as

java.util.Enumeration  enum;

The java.util.Enumeration class has been obsoleted by a class called Iterator, also in the java.util package, so if you're updating some code to change a variable called "enum", you might want to modify it to use an iterator too. We cover iterators in Chapter 16.

Before JDK 1.5, a common way to represent enumerations was with integer constants, like this:

class Bread {
    static final int wholewheat = 0;
    static final int ninegrain = 1;
    static final int rye = 2;
    static final int french = 3;
}

then later

int todaysLoaf = rye;

In the new enum scheme, enumerations are references to one of a fixed set of objects that represent the various possible values. Each object representing one of the choices knows where it fits in the order, its name, and optionally other information as well. Because enum types are implemented as classes, you can add your own methods to them!

The main purpose of this chapter is to describe enumerated types in detail. To do that, we first need to explain what the field modifiers "static" and "final" mean. Here's the story in brief:

  • The keyword final makes the declaration a constant.

  • The keyword static makes the declaration belong to the class as a whole. A static field is shared by all instances of the class, instead of each instance having its own version of the field. A static method does not have a "this" object. A static method can operate on someone else's objects, but not via an implicit or explicit this.

    The method where execution starts, main(), is a static method. The purpose of main() is to be an entry point to your code, not to track the state of one individual object. Static "per-class" declarations are different from all the "per-object" data you have seen to date.

The values in enumerated types are always implicitly static and final. The next two sections, What Field Modifier static Means and What Field Modifier final Means, have a longer explanation of the practical effect of these field modifiers. After that, we'll get into enumerated types themselves.

What Field Modifier static Means

We have seen how a class defines the fields and methods that are in an object, and how each object has its own storage for these members. That is usually what you want.

Sometimes, however, there are fields of which you want only one copy, no matter how many instances of the class exist. A good example is a field that represents a total. The objects contain the individual amounts, and you want a single field that represents the total over all the existing objects of that class. There is an obvious place to put this kind of "one-per-class" field too—in a single object that represents the class. Static fields are sometimes called "class variables" because of this.

You could put a total field in every object, but when the total changes you would need to update every object. By making total a static field, any object that wants to reference total knows it isn't instance data. Instead it goes to the class and accesses the single copy there. There aren't multiple copies of a static field, so you can't get multiple inconsistent totals.

Static is a really poor name

Of all the many poorly chosen names in Java, "static" is the worst. The keyword is carried over from the C language, where it was applied to storage which can be allocated statically (at compile time). Whenever you see "static" in Java, think "once-only" or "one-per-class."

What you can make static

You can apply the modifier static to four things in Java:

  • Data. This is a field that belongs to the class, not a field that is stored in each individual object.

  • Methods. These are methods that belong to the class, not individual objects.

  • Blocks. These are blocks within a class that are executed only once, usually for some initialization. They are like instance initializers, but execute once per class, not once per object.

  • Classes. These are classes that are nested in another class. Static classes were introduced with JDK 1.1.

We'll describe static data and static methods in this chapter. Static blocks and static classes are dealt with later on.

Static data

Static data belongs to the class, not an individual object of the class. There is exactly one instance of static data, regardless of how many objects of the class there are. To make a field "per-class," apply the keyword "static," as shown here.

class Employee {
     int    id;                    // per-object field
     int    salary;                // per-object field

     static int total; // per-class field (one only)

           ...
}

Every Employee object will have the employee_id and salary fields. There will be one field called totalPayroll stored elsewhere in an object representing the Employee class.

Because static data is declared in the class right next to the instance data, it's all too easy to overlook that static data is not kept in each object with its instance data. Make sure you understand this crucial point before reading on. Figure 6-1 represents the previous code in the form of a diagram.

06fig01.gifFigure 6-1 There is one copy of a Static field, shared by each object37810 FN Figure 6-1

In methods inside the class, static data is accessed by giving its name just like instance data.

salary = 90000;
total = this.total + this.salary;
   

It's legal but highly misleading to qualify the name of a static field with "this." The "this" variable points to an instance, but static data doesn't live in an instance. The compiler knows where the static data really is, and generates code to access the field in the class object.

Outside the class, static data can be accessed by prefixing it with the name of the class or the name of an object reference. It is considered poor form to use the object reference method. It confuses the reader into mistaking your static member for an instance member.

Employee newhire = new Employee();

// static reference through the class (preferred)
   Employee.total += 100000;
   

Static methods

Just as there can be static data that belongs to the class as a whole, there can also be static methods, also called class methods. A class method does some class-wide operations and is not applied to an individual object. Again, these are indicated by using the static modifier before the method name.

The main() method where execution starts is static.

public static void main(String[] args) {
   

If main weren't static, if it were an instance method, some magic would be needed to create an instance before calling it, as is done for applets and servlets.

Any method that doesn't use instance data is a candidate to be a static method. The conversion routines in the wrappers for the primitive types are static methods. If you look at the source code for java.lang.Integer, you'll see a routine like this

public static int parseInt(String s)
   throws NumberFormatException {
   // statements go here.
   }
   

The method is a utility that reads the String passed to it as an argument, and tries to turn it into an int return value. It doesn't do anything with data from a specific Integer object (there isn't even an Integer object involved in the call). So parseInt() is properly declared as static. It wouldn't be actively harmful to make it an instance method, but you would then need to whisk up an otherwise unnecessary Integer object on which to invoke it. Here's an example of calling the static method parseInt:

int i = Integer.parseInt("-2048");

The Java Language Specification says "A class method is always invoked without reference to a particular object" (section 8.4.3.2). So some compilers generate an error if you invoke a static method through an instance variable. Other compilers take the view "it's OK to reach static data through an instance reference (and the JLS has an example of this), so it should be OK for static methods too". Stick to invoking static methods using the class name, to avoid compiler problems and to show other programmers that this a class method.

A common pitfall with static methods

A common pitfall is to reference per-object members from a static method. This "does not compute". A static method isn't invoked on an object and doesn't have the implicit "this" pointer to individual object data, so the compiler won't know which object you want. You'll get an error message saying "Can't make static reference to non-static variable."

Java novices often make this mistake when they write their first class with several methods. They know the main() method has to be static, but they try to invoke the instance methods from inside main. The simplest workaround is to declare an instance of the class in question inside main(), and invoke the methods on that.

class Timestamp {
    void someMethod() { // ...

    public static void main(String[] args) {
      someMethod(); // NO! does not work
      
      Timestamp ts = new Timestamp();
      ts.someMethod(); // Yes! does work
      

Another workaround is to add the static modifier to everything you reference. Only use this kludge for small test programs.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020