使用通配符导入类 [英] importing classes using wildcards

查看:135
本文介绍了使用通配符导入类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我说:

import java.awt.event.ActionListener;

我得到了ActionListener类。
如果我说:

I get the ActionListener Class. If I say:

import java.awt.event.*;

我得到事件类包括 ActionListener?
或更好:

I get the event class including ActionListener? Or better yet:

import java.awt.*;

我认为如果你包括一个类,就像在前两个例子中那样,你有效地导入了class并继承了它的所有子类。但是,当我仅使用最后一行时,例如,Eclipse经常会显示错误,说它无法解析某些项目,并建议我将两者包含在java.awt和java.awt.event中。

I thought that if you included a class, like in the last two example, that you effectively imported that class and inherited all of its subclasses. But, when I use only the last line, for example, Eclipse often shows errors saying it cannot resolve certain items and suggests I include both the java.awt and java.awt.event.

推荐答案

Java中的通配符导入仅适用于实现类的直接级别。

The "wildcard" imports in Java only work to the immediate level at which classes are implemented.

也就是说,如果您的课程 A B C ,具有完全限定名称:

That is, if you have classes A, B and C, with fully qualified names:


  • com.foo.bar。 A ;

  • com.foo.bar.B ;

  • com.foo.C ;

  • com.foo.bar.A;
  • com.foo.bar.B;
  • com.foo.C;

然后导入 com.foo.bar。* 将允许访问 A B 更进一步;但 C 将无法使用。

then importing com.foo.bar.* will allow access to A and B without further ado; but C will NOT be available.

同样,导入 com.foo 。* 可以随时使用 C ,但不能 A B

In the same vein, importing com.foo.* will readily have C available, but not A and B.

现在:


I认为如果你包括一个类,就像在前两个例子中那样,你有效地导入了该类并继承了它的所有子类。

I thought that if you included a class, like in the last two example, that you effectively imported that class and inherited all of its subclasses.

它没有。即使 B 继承 A ,如果您选择使用完全限定的导入 com .foo.bar.A ,它不会自动导入 com.foo.bar.B 。您必须单独导入 B 。这是有道理的:没有什么能迫使接口或抽象类的实现与它们的基本接口/基类在同一个包中;在同一个项目中,你可能有两个名为 B 的类,在不同的包中:编译器应该做什么?

It does not. Even if B "inherits" A, if you choose to use the fully qualified import com.foo.bar.A, it WILL NOT automatically import com.foo.bar.B. You'll have to import B separately. Which makes sense: nothing forces implementations of an interface or abstract class to be in the same package as their base interface/base class, for one; and in the same project, you may have two classes named B, in different packages: what should the compiler do?

现在,根据您自己弥补或必须在工作环境中服从的编码风格约定,这些通配符导入可能纯粹而且简单地被禁止,并且您必须导入 A B 分开。至于静态导入,它们还有其他问题......

Now, according to coding style conventions, which you either make up for yourself or have to obey in your work environment, such wildcard imports may be purely and simply forbidden, and you'll have to import A and B separately. As to static imports, they have other problems...

最后,请注意,默认情况下,您可以使用所有 java.lang。* ,无需申报进口。

Finally, note that by default, you can use all of java.lang.* without having to declare an import.

这篇关于使用通配符导入类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆