Java Class Protection
I suspe开发者_JS百科ct the answer is no, but I want to check. If I have this structure in a Java application:
-package
-ClassA
-subpackage
-ClassB
-subsubpackage
-ClassC
I want package.subpackage.ClassB to have access to package.subpackage.subsubpackage.ClassC, but I don't want package.ClassA to have access to package.subpackage.subsubpackage.ClassC. Is there any way to enforce this?
No, the only access modifiers are:
public
- global accessprotected
- package and subclass access- "package-private" (no modifier) - package access
private
- class access only
protected
and package-private doesn't recursively grant access to subpackages. In short, subpackages don't really have any relationship with their parent package except for the fact that they share the same name prefix.
Here is a Java Specification Request that (I believe) deals with this issue: http://jcp.org/en/jsr/detail?id=294
This was supposed to be implemented in the just recently released Java 7, but apparently has been forgotten.
The only way that you can get this to work is through the use of inner classes. And, honestly, if that doesn't work then maybe you should be asking, "What is so important about C that A shouldn't be able to instantiate it but B and at least one other class can?"
No, there isn't. A package name is not an hierarchical construct If we have a class
foo.bar.Application
then bar
is not a child-package of foo
. The package is foo.bar
and there is no relation between foo
and foo.bar
, they are totally different packages (namespaces).
Making ClassC as an internal class for ClassB may solve your task.
No. The package hierarchy in Java has no effect on package visibility.
Things are either totally public or package-private.
There is no such thing as a "friend" package or a "parent" package here.
精彩评论