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 –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package com.codingraptor.java; import static java.Math.PI; // by virtue of statement above // Math.PI can simply be accessed as // PI public class Circle { // use PI to calculate area of a circle // note that method using static import // need not be static itself public double calculateArea(double radius) { // no need to say Math.PI return PI * radius * radius; } public double calculatePerimeter(double radius) { // no need to say Math.PI return PI * 2 * radius; }...} |
- 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
- Reduces the clutter. Allows you to use short names for methods and variables rather than fully qulified names.
- 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. - 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 .