views:

128

answers:

2

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.

+5  A: 

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.

Kaleb Brasee
Thanks a lot! I was wondering what default package meant. The answer has cleared it.
sana
A: 

Don't use default package. Just don't. Even sana.someapp.MyClass is better than default package. Packages are namespaces. Every class must be in a namespace, because sana.someapp.MyApplication is not the same as com.gurgitator.shakeitup.MyApplication.

George