Shouldn't “import foo.*” also include subpackage “foo.bar.*”?

后端 未结 3 1983
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 08:22

Studying Java, I\'ve thought about a, to me, rather confusing property of many tutorials. Consider the following two imports from a sample tutorial:

import j         


        
相关标签:
3条回答
  • 2021-01-12 08:48

    See my answer here (and my comment). A wildcard only goes 1 level deep, not into subpackages

    0 讨论(0)
  • 2021-01-12 08:52

    Each package name ("a.b.c") is a discrete package. Two packages with similar naming prefix ("a.b.c" and "a.b.d", for example) are separate packages for the language, both for namespaces and for access control.

    For humans, of course, this represents a possible relation between the packages.

    0 讨论(0)
  • 2021-01-12 08:55

    No, packages are taken as a whole. Even though it's often useful to think of them hierarchically, there is no notion within the Java language or compilation that says java.awt.event belongs to java.awt.

    Your comparison with SQL tables isn't quite right because there's no such thing as a sub-table in SQL databases. Instead, imagine you had a table representing all your classes, with the following entries:

    ID | Package   | Name
    --------------------------
    1  | awt       | SomeClassName1
    2  | awt.event | SomeClassName2
    

    Now, if you wanted to get awt classes, you'd say:

    SELECT * FROM MyTable WHERE Package = 'awt'
    

    You wouldn't expect this to give you both entries, just because the package name starts with awt, would you?

    0 讨论(0)
提交回复
热议问题