Packages and static imports in Java

Use packages and static imports to organize top-level types and simplify access to their static members

1 2 3 Page 3
Page 3 of 3

First, when two static imports import the same-named member, the compiler reports an error. For example, suppose package physics contains a Math class that's identical to java.lang's Math class in that it implements the same PI constant and trigonometric methods. When confronted by the following code fragment, the compiler reports errors because it cannot determine whether java.lang.Math's or physics.Math's PI constant is being accessed and cos() method is being called:


import static java.lang.Math.cos;
import static physics.Math.cos;

double angle = PI;
System.out.println(cos(angle));

Second, overusing static imports pollutes the code's namespace with all of the static members you import, which can make your code unreadable and unmaintainable. Also, anyone reading your code could have a hard time finding out which type a static member comes from, especially when importing all static member names from a type.

Conclusion

Packages help you create reusable libraries of reference types with their methods. If you should call a method (whether packaged into a library or not) with an illegal argument (such as a negative index for an array), you'll probably run into an exception. My next Java 101 tutorial introduces Java exceptions. Jump to that article when you are ready to explore Java's language features for writing code that works, even when exceptions occur.

This story, " Packages and static imports in Java" was originally published by JavaWorld.

Copyright © 2020 IDG Communications, Inc.

1 2 3 Page 3
Page 3 of 3