Search code examples
javapackagepackage-private

Package-private class visible to some other packages (with same name) under a different source folder


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

Solution

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