Edward Ruchevits
Edward Ruchevits

Reputation: 6696

Import Java classes once for all package

Let's say, I have the following structure:

I want all classes from first package to be imported in all classes in my second package.

Now I'm just specifying for every class in second package:

import first.*;

Can I import once for all classes in package?

Upvotes: 2

Views: 3977

Answers (3)

Stephen C
Stephen C

Reputation: 718788

Can I import once for all classes in package?

No you can't. Imports only apply to the class source file in which they are declared.

Maybe I can create some superclass with import statements and then extend it every time?

That will only work if the code in the subclasses does not mention the names of the external types at all ... which is rarely possible.

As I said imports only apply to the class source file in which they are declared.


Actually, the import was deliberately designed to work this way. The idea is to allow you to easily figure out what class a classname refers to. (It works best if you don't use star imports ...)

Upvotes: 1

duffymo
duffymo

Reputation: 308763

No, it cannot be done.

I don't see why this is such a hardship.

A better solution would be to use an IDE that can add the imports as you need them.

I'd also recommend spelling each one out individually rather than using the star notation, even if you need to import all of them. It documents your intent better, and that IDE can make it transparent to you.

Upvotes: 5

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181280

No, you can't do that in Java.

One thing that you might think of doing is moving classes from second package to first so you won't need the imports. But I understand that that is not always possible/desirable.

Upvotes: 2

Related Questions