开发者

Java Class Protection

开发者 https://www.devze.com 2023-03-27 02:30 出处:网络
I suspe开发者_JS百科ct the answer is no, but I want to check. If I have this structure in a Java application:

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 access
  • protected - 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消