不同包中的类名相同
同一类可以存在于多个包中吗? 换句话说,我可以在 com.test.package1
和 com.test.package2
中拥有 Foo.java
类吗?
更新
现在,我从包 1 中复制了类,并将其放入包 2 中,现在我正在创建该类的一个实例,我希望该实例指向包 1 中存在的类,但目前它指向包 1路径,请问如何修改?
哦,所以我不能做这样的事情:
Foo = new Foo() // pointing to Foo class in package 1
Foo = new Foo() // pointing to Foo class in package 2
Can same class exist in multiple packages?
In other words, can I have Foo.java
class in com.test.package1
and com.test.package2
?
Update
Now I copied class from package 1 and placed in to package 2 and now I am creating an instance of that class, I want this instance to point to class present in package 1 but currently it points to package1 path, how can i modify it?
Oh so I cannot do something like:
Foo = new Foo() // pointing to Foo class in package 1
Foo = new Foo() // pointing to Foo class in package 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,您可以在多个包中拥有两个同名的类。但是,您无法使用两个
import
语句在同一文件中导入这两个类。如果您确实需要引用两个类名,则必须完全限定其中一个类名。示例:假设您有
pkg1/SomeClass.java
pkg2/SomeClass.java
和 Main.java
如果您尝试编译,您将得到:
但是确实可以编译:
Yes, you can have two classes with the same name in multiple packages. However, you can't import both classes in the same file using two
import
statements. You'll have to fully qualify one of the class names if you really need to reference both of them.Example: Suppose you have
pkg1/SomeClass.java
pkg2/SomeClass.java
and Main.java
If you try to compile, you'll get:
This however does compile:
当然可以,但如果两者都包含在源文件中,则在其他包中调用它们时您需要区分您想要哪一个。
对评论的回应:
Sure can but you'll need to distinguish which one you want when calling them in other packages if both are included within a source file.
Response to Comment:
当我遇到错误
单类型导入已经定义了具有相同简单名称的类型
时,我被谷歌带到了这个页面。我通过意识到行import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
已经潜入了最顶部来修复了这个错误(经过很长一段时间)我的导入,而我的导入底部有行import org.apache.commons.codec.binary.Base64;
。i was taken to this page by google when i had the error
a type with the same simple name is already defined by the single-type-import
. i fixed this error (AFTER A VERY LONG TIME) by realising the lineimport com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
had snuck into the very top of my imports whilst i had the lineimport org.apache.commons.codec.binary.Base64;
at the bottom of my imports.因此,我正在寻找一种更智能的解决方案,而不仅仅是在一个或两个已实现的类上使用完全限定名称。
如果您创建一个私有类并扩展您的类,您可以自由使用该类,而无需每次都编写完整的包名称。
包1
包2
我的类实现
So I was looking for a smarter solution than just using fully qualified names on one or both of the implemented classes.
If you create a private class, and extend your class, you are free to use the class, without writing the full package name each time.
Package 1
Package 2
My class implementation