Presents your JAVA E-NEWSLETTER for April 1, 2004 <-------------------------------------------> TIPS ON USING JAVA 1.5'S NEW STATIC IMPORT FEATURE Java 1.5's static import feature allows you to import the static members of an interface or class. The purpose of this feature seems to be to prevent programmers from making the mistake of using the "Constant Interface antipattern." HOW IT WORKS To import the static members (i.e., attributes, methods, classes) of a class or interface, you use the import keyword with the static modifier: import static tips.Constants.*; Here is the definition of the Constants type: package tips; public interface Constants { public static final int PORT_NUMBER = 90; public static final String APP_NAME = "DOOLY"; public static class StaticNestedClass {} } By using import static, the class can now use the static members without specifying the Constants class name. For example: import static tips.Constants.*; public class StaticImportTip { public static void main(String []args) { System.out.println(PORT_NUMBER); System.out.println(APP_NAME); System.out.println(StaticNestedClass.class); } } If you decide to use the new static import feature, I recommend importing the constant names individually instead of using the wildcard. This serves to give the constant some perspective. For instance, in the snippet below, a developer scanning the source code won't know from which type the DEFAULT_URL or PORT_NUMBER constants are being imported. import static tips.Constants.*; import static tips.gen.App.*; public class StaticImportTip { public static void main(String []args) { System.out.println(PORT_NUMBER); System.out.println(DEFAULT_URL); } } If the import statements look like this: import static tips.Constants.PORT_NUMBER; import static tips.gen.App.DEFAULT_URL; then the source of the constant becomes obvious. This is my opinion; if you have a different one, please send us an e-mail and let us know. (Please include "Java: Static import feature" in the subject line.) mailto:Enews2@cnet.com NOTE: The code in this tip was compiled on Windows 2000 using Java build 1.5.0-beta-b32c. To compile the code, you must use the javac "-source 1.5" option. David Petersheim is the Director of Application Development with Genscape, Inc. He designs and develops server-side applications to acquire and process real-time energy data. ----------------------------------------