Nested packages in Java

此生再无相见时 提交于 2019-12-01 20:15:47

问题


Firstly I want to create a custom user library with the following structure:

src:

  • LibA.pack1
    • ClassName0.java
  • LibA.pack2
    • ClassName1.java

I have no problem with this one. Later I want to import this library into the other project and call

import LibA.*;

(to use both classes of pack1 and pack2), which will fail as it requires full name, i.e.

import LibA.pack1;

How can I import the whole library at once to be able to use both classes of pack1 and pack2?

P.s. It's definitely not called "nested packages" but I have no idea how to call this. P.p.s. I'm using Eclipse if it matters.

Thanks in advance:)


回答1:


You can't, since there is no such thing as nested packages in java. You must import both packages explicitly.

import LibA.pack1.*;
import LibA.pack2.*;

LibA.pack1 is not related in any way to LibA.pack2, and both of them have no relation to LibA package, so if LibA has additional classes you wish to import, you'll need a 3rd import :

import LibA.*;

Apparent Hierarchies of Packages

At first, packages appear to be hierarchical, but they are not. For example, the Java API includes a java.awt package, a java.awt.color package, a java.awt.font package, and many others that begin with java.awt. However, the java.awt.color package, the java.awt.font package, and other java.awt.xxxx packages are not included in the java.awt package. The prefix java.awt (the Java Abstract Window Toolkit) is used for a number of related packages to make the relationship evident, but not to show inclusion.

Importing java.awt.* imports all of the types in the java.awt package, but it does not import java.awt.color, java.awt.font, or any other java.awt.xxxx packages. If you plan to use the classes and other types in java.awt.color as well as those in java.awt, you must import both packages with all their files:

import java.awt.*;
import java.awt.color.*;


来源:https://stackoverflow.com/questions/26509219/nested-packages-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!