为什么子包看不到包私有类?
好吧,我有这个项目结构:
package AB
- class
SuperClass
(此类被标记为包私有)
package ABC
- class
SubClass
(从超类继承)
我宁愿不让 SuperClass
公开可见...它实际上只是这个特定项目 (AB) 的实用程序类。
在我看来,SubClass 应该能够看到 SuperClass
,因为包 ABC 是 AB 的子包..但事实并非如此。
解决这个问题的最佳方法是什么?我认为将 ABC 中的所有内容向上移动到 AB 或将 AB 向下移动到 ABC 是没有意义的。主要是因为可能会有一个 ABD 也继承自 AB 中的内容...
我对此有点陌生Java,所以要友善一些:D(我是 C++ 和 .NET 人员)
Okay so, I have this project structure:
package A.B
- class
SuperClass
(this class is marked package private)
package A.B.C
- class
SubClass
(inherits from super class)
I'd rather not make SuperClass
publicly visible... It is really just a utility class for this specific project (A.B).
It seems to me that SubClass should be able to see SuperClass
, because package A.B.C is a subpackage of A.B... but this is not the case.
What would be the best way to resolve this issue? I don't think it makes sense to move everything in A.B.C up to A.B or move A.B down to A.B.C... mainly because there will probably be an A.B.D which inherits from stuff in A.B as well...
I'm a bit new to Java, so be nice :D (I'm a C++ and .NET guy)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
包是唯一标识符。你不能让他们遵守继承规则。 Package 和 SubPackages 与 Super 和 Sub 类不同。
我没有看到使您想要在子包中使用的类对外界可见的任何缺陷。我有兴趣知道这个标准在 C++/.net 中是如何处理的(因为我是一个 java 人:))
Packages are unique identifiers. You cannot make them follow the inheritance rules. Package and SubPackages are not analogical to Super and Sub classes.
I dont see any flaws in making the class that you wanted to use in the sub package to be visible to the outside world. I would be interested to know how this criterion is handled in C++/.net (as I am a java guy :) )
最好的选择是将
SuperClass
的(默认)构造函数声明为protected
。这样,只有同一包中的类和子类(无论包如何)才能实例化它并从中扩展。Your best bet is to declare the (default) constructor(s) of
SuperClass
asprotected
. This way only classes in the same package and subclasses regardless of the package can instantiate it and extend from it.为什么不把它们放在同一个包级别呢?
你能以某种方式使用组合而不是继承吗?在阅读了《Effective Java》之后,我一直在尝试自己做更多的事情。不确定这是否可能考虑到您的需求,但可能值得考虑。
祝你好运。
Why not put them in the same package level?
Could you somehow use composition instead of inheritance? I've been trying to do more of this myself after reading Effective Java. Not sure if this is possible given your needs, but it might be worth considering.
Good luck.