In Java- "Static Members of the default package cannot be imported"- Can some one explain this statement? It would be better if its with an example. I am not sure if it has a really simple answer but then I tried to understand but couldn't figure it out.
NOTE : System is a class present in java. lang package and out is a static variable present in System class. By the help of static import we are calling it without class name.
There are problems on many different levels: you can't import classes in the default package from classes that are not. you will get class loading problems if you try to resolve the default package in multiple artifacts. you can no longer use the default and protected scope like you normally can.
Static import is a feature introduced in the Java programming language that allows members (fields and methods) which have been scoped within their container class as public static , to be used in Java code without specifying the class in which the field has been defined.
What is the difference between import and static import? The import allows the java programmer to access classes of a package without package qualification whereas the static import feature allows to access the static members of a class without the class qualification.
It means that if a class is defined in the default package (meaning it doesn't have any package definition), then you can't import it's static methods in another class. So the following code wouldn't work:
// Example1.java
public class Example1 {
public static void example1() {
System.out.println("Example1");
}
}
// Example2.java
import static Example1.*; // THIS IMPORT FAILS
public class Example2 {
public static void main(String... args) {
example1();
}
}
The import fails because you can't import static methods from a class that's in the default package, which is the case for Example1. In fact, you can't even use a non-static import.
This bug report has some discussion about why Java acts this way, and it was eventually closed as "not a defect" -- it's the way Java was designed to behave. Default package just has some unexpected behavior, and this is one of the reasons why programmers are encouraged to never used the default package.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With