Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can import statements be used anywhere besides the beginning of a Java file?

In python, the import statement can be placed everywhere in the file, even inside a class, or an if.

Is there a way to accomplish the same thing in Java? I understand that it could be a bad practice not to put all the imports at the top of the file, I'm just wondering if it is possible in some way or not.

like image 896
enrico.bacis Avatar asked Jan 26 '16 11:01

enrico.bacis


1 Answers

The very first statement in a Java file must be (if there is one) the package statement, followed by the import statements. They can not be placed in another location.

However, it is possible to skip the import altogether by using fully qualified class names (which I personally don't recommend). You need to use them everywhere you would have used the short, unqualified name.

import my.package.MyClass;

public class Test{
    private MyClass instance = new MyClass();
}

can be rewritten as:

public class Test{
    private my.package.MyClass instance = new my.package.MyClass();
}
like image 130
Stultuske Avatar answered Oct 13 '22 02:10

Stultuske