Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java- "Static Members of the default package cannot be imported"- Can some one explain this statement?

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.

like image 995
MohamedSanaulla Avatar asked Dec 26 '09 18:12

MohamedSanaulla


People also ask

Can package be static in Java?

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.

Why should I avoid default packages in Java?

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.

What does static import do in Java?

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 difference between import and static import in Java?

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.


1 Answers

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.

like image 140
Kaleb Brasee Avatar answered Sep 18 '22 07:09

Kaleb Brasee