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"; } 

graphics/fridge_icon.jpg

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 ;


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.

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.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net