After 3 years of my programming life with Java, it was a really a surprise to me when I recently discovered that there is no concept of “sub-packages” at all in Java.
I was trying to disallow access to certain methods defined in a class to all classes residing outside the package. Of course, the default method access is the answer for this problem. However, to be exact, what I wanted to achieve was to allow access to classes residing in the so-called sub-packages and disallow the access to all other classes outside the package.
Though the package a.b is internally stored in a folder b within the folder a, to Java a and a.b are entirely different. The package structure is just for the developer to organize his codes in any logical way he wants. For the compiler they are totally irrelevant. It doesn’t care!
I couldn’t accept that this is a ‘feature’ in java. I was looking for some kind of exception or some way to allow access to some specific classes. But, my hours of search in the net ended in mere vain!
Then the reality struck and I realized that I am left with just 2 options to go about this condition:
- To make the methods as protected instead or package-private and inherit them in the sub-package classes.
- To move all the classes in the sub-package to the main package itself.
But the option 1 is not really a solution. Because by extending the class any other class residing any where else in the code base can inherit those methods – Which I really did not want to happen. So, I was forced to choose the option 2 and loose my package structure and code organization.
However, there is a news that this ‘might’ change from java 7. Take a look at this link (read the question 2.5 in section 2) giving the JSR request for more modularity. You may also wish to take a look at these articles which talk about the concept of super-packages intended to be introduced in Java 7:
This means, until the release of java 7, you just cant do anything about this – sub packages do not have any special relationship with their parent packages! 😦