When we
import any static method from other class we use static import. Let us take an
example –
import static
java.lang.System.out;
public class
Demo1 {
public static void
main(String[] args)
{
out.println("Hello java");
}
}
Output –
Hello java
Note – In
the above example System is a class whereas out is a static method, so we have
imported that method using import static java.lang.System.out; If we don’t give
static in import then it will give an error because to import any static method
we have to give static with import, and java.lang is a package name.
Example –
public class
Demo2 {
public static void
show()
{
System.out.println("I belong to Demo2 but executed in
Demo1");
}
}
import static
staticblock.Demo2.show;
public class
Demo1 {
public static void
main(String[] args)
{
show();
}
}
Output –
I belong to Demo2 but executed
in Demo1
No comments:
Post a Comment