Static import
Introduced in Java 5
Import statement was enhanced to provide greater keystroke-reduction
capabilities.
Static import is use
when you want to access Class static members.
Example:
File: First.java
import static
staticImport.Second.*;
public class First
{
public static void main(String[] args)
{
System.out.println(firstVar);
printfirstVar();
}
}
File : Second.java
public class Second
{
final static int firstVar= 34;
static void printfirstVar()
{
System.out.println(firstVar);
}
}
Output:
34
34
Problem:
Ambiguity of static members:
If we import from two classes which use same static
variables then compiler will in ambiguity to decide which variable class
variable to use.
Example:
File:First.java
import static staticImport.Second.*;
import static
staticImport.Third.*;
public class First
{
public static void main(String[] args)
{
System.out.println(firstVar); // Error since compile not able to
decide which firstVar we want to use, either of Second.java or Third.java
printfirstVar(); // Error: reason is same as
above
}
}
File: second.java
public class Second
{
final static int firstVar= 34;
static void printfirstVar()
{
System.out.println(firstVar);
}
}
File: Third.java
public class Third
{
final static int firstVar= 34;
static void printfirstVar()
{
System.out.println(firstVar);
}
}