Does anyone understand why Java is missing:
An access specifier which allows access by the class and all subclasses, but NOT by other classes in the same package? (Protected-minus)
An access specifier which allows access by the class, all classes in the same package, AND all classes in any sub-package? (Default-plus)
An access specifier which adds classes in sub-packages to the entities currently allowed access by protected? (Protected-plus)
I wish I had more choices than protected and default. In particular, I'm interested in the Protected-plus option.
Say I want to use a Builder/Factory patterned class to produce an object with many links to other objects. The constructors on the objects are all default, because I want to force you to use the factory class to produce instances, in order to make sure the linking is done correctly. I want to group the factories in a sub-package to keep them all together and distinct from the objects they are instantiating---this just seems like a cleaner package structure to me.
No can do, currently. I have to put the builders in the same package as the objects they are constructing, in order to gain the access to defaults. But separating project.area.objects from project.area.objects.builders would be so nice.
So why is Java lacking these options? And, is there anyway to fake it?
解决方案
To answer your questions one at a time:
* An access specifier which allows access by the class and all subclasses, but NOT by other classes in the same package? (Protected-minus)
This was in Java 1.0 (private protected was the modifier) and removed. I'm not entirely clear on why, but it was definitely viewed as something not worth the hassle. The current arrangement makes all modifiers go from less restricted to more restricted which is simpler (as in less potential variation) which is a Java design goal.
* An access specifier which allows access by the class, all classes in the same package, AND all classes in any sub-package? (Default-plus)
* An access specifier which adds classes in sub-packages to the entities currently allowed access by protected? (Protected-plus)
These two are not available for a related reason. Java currently doesn't have a notion of a sub-package, it just pretends to by the fact that the regular file and jar based classloaders (as well as the compiler) follow the directory structure of the underlying file system to find files. Java will be addressing this more extensively with JSR 294 (the "superpackage") (as others have pointed out) which will give you much more granular control of what is published outside of the package (and therefore you could make things public if you want to, and it still would not be visible).