在Java中,导入的类可以与导入的类具有相同的简单名称吗?有什么限制吗?
如果我在包 abc 中有一个类名 ClassX,并且我想导入类 abxClassX
Java 中是否有一些限制阻止我这样做?就用法而言,我始终可以使用导入类的完全限定名称,对吗?
Eclipse 似乎无法解决此导入问题,我需要知道 Java 本身是否存在导致问题的限制。
以下代码是否合法:
a\b\c\ClassX.java :
package a.b.c;
public class ClassX {
//
}
a\b\x\ClassX.java :
package a.b.x;
import a.b.c.ClassX;
public class ClassX {
public static void main(String[] args) {
a.b.c.ClassX newObj = new a.b.c.ClassX();
}
}
如果不合法,那么为什么?
If I have a class names ClassX in package a.b.c, and I want to import the class a.b.x.ClassX
Is there some restriction in Java preventing me from doing so? As far as usage goes, I can always use the fully qualified name of the imported class, right?
Eclipse seems to be unable to resolve this import, I need to know if there is a restriction in Java itself that is causing the problem.
Is the following code legal:
a\b\c\ClassX.java :
package a.b.c;
public class ClassX {
//
}
a\b\x\ClassX.java :
package a.b.x;
import a.b.c.ClassX;
public class ClassX {
public static void main(String[] args) {
a.b.c.ClassX newObj = new a.b.c.ClassX();
}
}
If no, then why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更准确地说,
尝试这样做将导致错误消息:
[NameOfImportingClass] 已在此编译单元中定义
。此限制的目的是防止名称歧义/冲突。
例如,如果没有导入,以下所有内容都是合法的:
现在让我们添加
import aB
如果 Java 无法阻止这种情况,则需要决定
B objectB
应表示什么类型。我们有两个选择:
bB
,因此键入导入。但这意味着要使用a
包中的B
,我们仍然需要将其编写为aB
,这意味着import aB ;
是冗余/死代码,只会让程序员感到困惑。aB
,因此输入导入。 但这会让人感觉不自然,因为在类 B{ }
中,B
会代表一些其他类型! 。上述解决方案都不好。
如果没有好的解决方案,最好的选择就是防止问题出现。
To be more precise
Attempting to do so will result in error message:
[NameOfImportingClass] is already defined in this compilation unit
.Purpose of this restriction is to prevent name ambiguity/clashes.
For example without imports all below is legal:
Now lets add
import a.B
IF Java would not prevent such situation, it would need to make decision what type
B objectB
should represent.We have two options:
b.B
so type which is importing. But that means to useB
froma
package we still would need to write it asa.B
, which meansimport a.B;
is redundant/dead code which would only be confusing programmers.a.B
so type which is imported. But that would feel unnatural since insideclass B{ }
,B
would represent some other type!.Neither of above solutions are good.
If there is no good solution to a problem, best option is to prevent from appearing.
我认为不行,但是不要写
abcClassx newObj = abcClassX()
,而是写abcClassX newObj = abcClassX()
(Class_X_,没有 Class_x_),它应该可以工作:-)I think no, but instead of
a.b.c.Classx newObj = a.b.c.ClassX()
, writea.b.c.ClassX newObj = a.b.c.ClassX()
(Class_X_, no Class_x_) and it should work :-)