Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Constants

Java programmers commonly define constants inside their interfaces, if it makes design sense. You can do so using variables in an interface because the values will be present instantly at runtime and their values shared among all classes implementing your interface, because they are static and final.

Here is how you do it.

public interface IDataAccessor {
  String DB_NAME = "Squishy";
}

Note that it only makes sense to define interface constants if the variables are tightly related to your interface definition. There is a pattern that has been popular among developers where they use interfaces for the sole purpose of defining constants, so you might come across a lot of code to that effect. But J2SE 5.0 introduces other mechanisms that are more appropriate for this sort of thing—namely typesafe enums and static imports.

Fridge

Like the public and abstract deal, interface variables are implicitly public, static, and final. That is, the following are equivalent within an interface: public static final String DB_NAME = "Squishy" and String DB_NAME = "Squishy". Likewise, you are not allowed to do this: private String x;

The reason that you don't want to use this old pattern anymore (assuming you're using it) is that it confuses the API. To access the constants defined in the interface, you must include implements InterfaceName in your class definition—and that isn't really true. You aren't implementing any functionality defined by such an interface; you just want the variables. It's a workaround, and now there are language features to handle that situation, so you don't have to resort to it.

  • + Share This
  • 🔖 Save To Your Account