Reputation: 7283
I suspect 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?
Upvotes: 2
Views: 266
Reputation: 36476
No, the only access modifiers are:
public
- global accessprotected
- package and subclass accessprivate
- class access onlyprotected
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.
Upvotes: 2
Reputation: 262824
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.
Upvotes: 1
Reputation: 82078
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?"
Upvotes: 2
Reputation: 114817
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).
Upvotes: 1