Static Imports In Java

Static Imports
If you have to access the static members of a class, then it is necessary to qualify the references with the class from which they come. This is also true of the enumeration type values.

J2SE version 5.0 provides the static import feature that enables unqualified access to static members without having to qualify them with the class name. Code 7 shows the use of static imports. Line 4 tells the compiler to include the enumerated type values (or any static member of that type) in the symbol table when compiling this program. Therefore, Line 9 can use SPADES without the Suit. namespace prefix. Code 7The TestPlayingCard Program Using Static Imports

1 package cards.tests;


3 import cards.domain.PlayingCard;

4 import static cards.domain.Suit.*;


6 public class TestPlayingCard {

7 public static void main(String[] args) {


9 PlayingCard card1 = new PlayingCard(SPADES, 2);

10 System.out.println(“card1 is the “ +


11 + “ of “ +



13 // NewPlayingCard card2 = new NewPlayingCard(47,


14 // This will not compile.

15 }

16 }

Caution – Use static imports sparingly. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all of the static members that you import. Readers of your code (including you, a few months after you wrote it) will not know from which class a static member comes. Importing all of the static members from a class can be very harmful to readability; if you need one or two members only, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.