When used like this:
import static com.showboy.Myclass;
public class Anotherclass{}
what's the difference between import static com.showboy.Myclass
and import com.showboy.Myclass
?
When used like this:
import static com.showboy.Myclass;
public class Anotherclass{}
what's the difference between import static com.showboy.Myclass
and import com.showboy.Myclass
?
See Documentation
Static import is used to import static fields / method of a class instead of:
You can write :
It is useful if you are often used a constant from another class in your code and if the static import is not ambiguous.
Btw, in your example "import static org.example.Myclass;" won't work : import is for class, import static is for static members of a class.
The
import
allows the java programmer to access classes of a package without package qualification.The
static import
feature allows to access the static members of a class without the class qualification.The
import
provides accessibility to classes and interface whereasstatic import
provides accessibility to static members of the class.Example :
With import
With static import
See also : What is static import in Java 5
The
static
modifier afterimport
is for retrieving/using static fields of a class. One area in which I useimport static
is for retrieving constants from a class. We can also applyimport static
on static methods. Make sure to typeimport static
becausestatic import
is wrong.What is
static import
in Java - JavaRevisited - A very good resource to know more aboutimport static
.The first should generate a compiler error since the static import only works for importing fields or member types. (assuming MyClass is not an inner class or member from showboy)
I think you meant
which makes all static fields and members from MyClass available in the actual compilation unit without having to qualify them... as explained above
Say you have static fields and methods inside a class called
MyClass
inside a package calledmyPackage
and you want to access them directly by typingmyStaticField
ormyStaticMethod
without typing each timeMyClass.myStaticField
orMyClass.myStaticMethod
.Note : you need to do an
import myPackage.MyClass
ormyPackage.*
for accessing the other resources