[英]Why can't sub-packages see package private classes?
Okay so, I have this project structure: 好的,我有这个项目结构:
package AB 包AB
SuperClass
(this class is marked package private) SuperClass
(此类标记为包私有) package ABC 包ABC
SubClass
(inherits from super class) SubClass
(继承自超类) I'd rather not make SuperClass
publicly visible... It is really just a utility class for this specific project (AB). 我宁愿不让
SuperClass
公开显示......它实际上只是这个特定项目(AB)的实用程序类。
It seems to me that SubClass should be able to see SuperClass
, because package ABC is a subpackage of AB.. but this is not the case. 在我看来,SubClass应该能够看到
SuperClass
,因为包ABC是AB的子包..但事实并非如此。
What would be the best way to resolve this issue? 解决此问题的最佳方法是什么? I don't think it makes sense to move everything in ABC up to AB or move AB down to ABC.. mainly because there will probably be an ABD which inherits from stuff in AB as well...
我不认为将ABC中的所有内容移至AB或将AB移至ABC是不合理的...主要是因为可能会有一个ABD继承AB中的内容...
I'm a bit new to Java, so be nice :D (I'm a C++ and .NET guy) 我对Java有点新意,所以要好看:D(我是C ++和.NET人)
Packages are unique identifiers. 包是唯一标识符。 You cannot make them follow the inheritance rules.
你不能让他们遵循继承规则。 Package and SubPackages are not analogical to Super and Sub classes.
Package和SubPackage与Super和Sub类不相似。
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 :) )
我很想知道如何在C ++ / .net中处理这个标准(因为我是一个java人:)
Your best bet is to declare the (default) constructor(s) of SuperClass
as protected
. 最好的办法是将
SuperClass
的(默认)构造函数声明为protected
。 This way only classes in the same package and subclasses regardless of the package can instantiate it and extend from it. 这样,只有相同的包和子类中的类,无论包是什么,都可以实例化它并从中扩展。
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.
在阅读Effective Java之后,我一直在努力做更多这方面的事情。 Not sure if this is possible given your needs, but it might be worth considering.
不确定这是否可以满足您的需求,但可能值得考虑。
Good luck. 祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.