To use static members (methods and variables) We must give the class that provides this static member.
Static import allows static variables and static methods of the imported class to be directly visible in the current class, using these static members without giving their class names.
Static import is also a new feature introduced by JDK5.0, and the following examples illustrate the use of static imports:
For example, define a class in a package first:
Package Com.example.learnjava;public class common{public static final int. age = ten; public static void output () { System.out.println ("Hello world!");} }
When used in another package , this is used if you do not use a static import:
Package Com.example.learnjava2;import Com.example.learnjava.common;public class staticimporttest{public static void Main (string[] args) { int a = Common.age; System.out.println (a); Common.output (); }}
The import statement was added earlier, the common class is imported , and the static member variable and static method are used to add the class name .
Using static Import
The syntax for static import is:
Import static package name. class name. static member variable;
Import static package name. class name. static member function;
Note the member variables and method names are imported.
After using static import as the previous program:
Package Com.example.learnjava2;import static Com.example.learnjava.common.age;import static Com.example.learnjava.common.output;public class staticimporttest{public static void Main (string[] args) { int a = age; System.out.println (a); Output (); }}
Disadvantages
Excessive use of static imports can reduce the readability of your code to some extent.
Resources
Long Zhang Teacher Java SE Series video tutorial.
Original address: http://www.cnblogs.com/mengdd/archive/2013/01/23/2873312.html
Java static import to the static import