We
can use an import statement to import classes and interface of a
particular package. Whenever we are using import statement it is not required
to use the fully qualified name and we can use short name
directly. We can use static import to import static member from
a particular class and package. Whenever we are using static
import it is not required to use the class name to access static
member and we can use directly.
Static Import
:
• Static import is new feature
introduced in java.
• In java, with the help of
static import, we can access the static members of a class directly without
class name or any object.
• Static packages must be
import by using static keyword.
• According to Sun Microsystem,
it will improve the code readability and enhance coding, but according to the
programming experts, it will create too much confusion and not good for
programming.
• If there is no requirement
we should not go for static import.
• If user wants to access any
static member of class then less coding is required.
• Static import makes the
program unreadable and unmaintainable if you are reusing this feature.
• Following is a simple example
to use static imports:
// System class without
Class name
import static java.lang.Math.*;
import static java.lang.System.*;
class A
{
public
static void main(String[] args)
{
//
We are calling static member of System class
//
directly without System class name
out.println(sqrt(4));
out.println(pow(2,
2));
out.println(abs(-6.3));
}
}
Output : -
2.0
4.0
6.3
According to above example we import two
static packages :
1. import static
java.lang.Math.*;
2. import static
java.lang.System.*;
Using this static imports we can directly call
methods of static class in java such as sqrt, pow, abs etc are methods of
static class Math and out.print is method of static class System.
Normal Import
:
• We can use an import
statement to import classes and interface of particular package.
• To access a class or method from another packages, we
need to use the fully qualified name or we can use import statement it is known
as normal import.
• In java, the ‘java.lang’ package
is default package, which automatically imported into our code by java.
• Following are some normal
import packages list :
• Import java.util.*;
• Import java.io.*;
• Import java.awt.*;
• Import java.text.*; and etc.
• Following is a simple
example to use normal imports :
import java.util.*;
class A
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print(“Enter No =
”);
Int no = s.nextInt();
System.out.print(“Number
is = ”+no);
}
}
According to above example import java.util.*; is a one type of normal import.