简体   繁体   中英

Does the star import include subpackages in Java?

When you declare an import like this:

import com.microsoft.azure.storage.*;

Does that include everything in its subpackages too? For example, does it include this?

import com.microsoft.azure.storage.blob.*

If not, why not? (Edit: the "why" question is basically off topic. ignoring that bit when considering a correct answer.)

No it does not. It only imports everything in the package (ie the directory itself). Sub-directories are considered to be different packages, so you would need to:

import com.microsoft.azure.storage.*
import com.microsoft.azure.storage.blob.*

As to why the language designers chose to go this route, one can only guess, but the system that they decided to go with does allow for a more fine-grained approach.

yes you can import all the classes from an import but it does not make it possible to import multiple packages with similar names. For example import java.util*; does not also import java.util.prefs or .jar you have to import these all separately. I don't know if that answers your question, and to the why I am not really sure it just makes sense to do it this way. If you were to import similar packages that had the same static variables, but you only need two or three of the packages then you would get errors or code that does not run properly.

There's a name for these - type import on demand .

A type-import-on-demand declaration allows all accessible types of a named package or type to be imported as needed.

They're only also importing the package itself, and not any subpackages, as clarified by the example, emphasis mine:

import java.util.* ;

causes the simple names of all public types declared in the package java.util to be available within the class and interface declarations of the compilation unit. Thus, the simple name Vector refers to the type Vector in the package java.util in all places in the compilation unit where that type declaration is not shadowed (§6.4.1) or obscured (§6.4.2).

does that include everything in / subdirectories too? including something like this?

* stands for all the compilation units inside the package com.microsoft.azure.storage where sub packages are actually not compilation units and thus not fetched when you write myPack.* . Compilation unit includes class , interface , enum etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM