static import in Java

A static import allows you to access static members (both methods and instance variables) of a class possibly located in  different package. Much like the import statement discussed earlier, the static import is also a syntactic sugar. By using an import statement you can avoid writing package names before classes and interfaces. Similarly, by using static import you avoiding writing both package and class names before static members. This kind of import was introduced in Java 5 (Tiger).

Examples of static import

The following example demonstrates how to use static import –

  • The first point to note here is that static import is written as

/* a static import template */

import static packagename.ClassName.staticMember;

  • As you can see from the code above,  import is a convenience feature. Even without it we could have calculated the area and perimeter of circle. Just that it would have meant a few extra keystrokes and some extra code to read for the maintainer later on.
  • Both instance and static members of class can use the member that has been statically imported.

Pros and Cons of static import

  1. Reduces the clutter. Allows you to use short names for methods and variables rather than fully qulified names.
  2. Like other imports, it can create readability and maintenance problems. For example, it is much better to say Math.PI rather than simply PI.
    A close realy world analogy would be saying John instead of John F. Kennedy. To most people John is a common noun and John F. Kennedy a household name.
  3. Introduces chances of name conflict. Once you have statically imported Math.PI and start calling it PI, you cannot statically import another member called PI. For example, you may have your own Math class where perhaps the value of π  is more precise. You cannot statically import both these π. But you can import your class and use both π  by saying Math.PI or MyClass.PI .

Leave a comment

Your email address will not be published. Required fields are marked *