1

When I was doing some testing with packages and package-private classes in Java, I noticed an interesting thing. The following is my projects source structure, the class MyTestClass.java in package com.test.pkg under source folder src is a package-protected class. As per my understanding, this should not be accessible outside this package. But, interestingly MyTestClass.java class is accessible in com.test.pkg under source folder test as well. This happens only if the package names are same, though they are in different source folders.

Can someone tell me why this happens ?

TestProject
|
-src
  -com.test.pkg
    -MyTestClass.java
-test
  +com.test.pkg
k0der
  • 137
  • 1
  • 10
  • 1
    And why not, it is the same package... Doesn't matter if they are in different directories or jars. It is the same package regardless. – M. Deinum May 25 '15 at 10:48
  • Thank for the info. If so, what is the use of source of source folders (src, test in this case). Is that just for organizing purpose ? – k0der May 25 '15 at 10:51
  • @k0der - When you `import` classes, do you inlcude `src` in the class path?. Nope right?. You start from `com.test....`. So, `src` and `test` are at the same level and represent a `global` parent directory. So, the package will be the same. – TheLostMind May 25 '15 at 10:54
  • That is for organizing only to separate your test and application code... – M. Deinum May 25 '15 at 10:56

1 Answers1

3

The source directory does not matter at all in this case. What is important: the packages names are the same, hence the both classes belong to the same package - everything is correct.

dstronczak
  • 2,406
  • 4
  • 28
  • 41
  • Thank for the info. If so, what is the use of source of source folders (src, test in this case). Is that just for organizing purpose ? – k0der May 25 '15 at 10:53
  • Yes, exactly. Ussually you keep your actual code in the src folder, and the test classes in the test folder (although both the actual class and the testing class belong in the same package obviosly). If you kept them in the same folder there would be a mess and you would not be able to quicly distinguish test classes from the actual classes. – dstronczak May 25 '15 at 10:54