Static Imports In Java




Static Imports
import-static
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;

2

3 import cards.domain.PlayingCard;

4 import static cards.domain.Suit.*;

5

6 public class TestPlayingCard {

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

8

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

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

card1.getRank()

11 + “ of “ +

card1.getSuit().getName());

12

13 // NewPlayingCard card2 = new NewPlayingCard(47,

2);

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.


One thought on “Static Imports In Java

  1. I was very happy to search out this web-site.I wanted to thanks on your time for this wonderful learn!! I positively enjoying every little bit of it and I have you bookmarked to check out new stuff you blog post.

Comments are closed.