0

I have programmed in Java for some time and I just realized that the protected access modifier allows members to be accessed also in the same package. So here is the situation and the question:

I have a class having a protected method, and a test class using Mockito to stub that method. The two classes are located in different folders (a src and a test), but their package names are the same! The funny thing is, I can call the protected method in the test class! I would like to know how it is possible? Because their package names are the same? In this case the protected modifier does allow a very wide access!

Weixiang Guan
  • 457
  • 2
  • 6
  • 16
  • 1
    Finally all the classes of `src` and `test` goes to `bin` target folder. see the classes there. – Braj Aug 21 '14 at 08:39
  • It doesn't matter that the classes are located in *src* and *test*. At Runtime, all the classes which have the same package name, will be considered are classes from one and the same package. Try to change the package of the test class and you will see that you won't be able to access the `protected` method. – Konstantin Yovkov Aug 21 '14 at 08:40

2 Answers2

1

If the package names are the same, the two classes are in the same package - it's as simple as that. The fact that they were built from different source directories is irrelevant - the only thing that identifies a package is its fully-qualified name.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Package name means directory structure inside which .class file will be placed by compiler. If two java files with same package name but different package(don't know how) will be compiled, they will be placed in same directory.

And protected fields will be accessible.

In short, you cannot have same package name for different package, java will treat them as same package.

codingenious
  • 8,385
  • 12
  • 60
  • 90
  • Having read the answers of you guys I think I understand now. FYI, as I said in the question, I have a *src* folder and a *test* folder, and some of the packages in the two folders have the exact same name, that's why I have two packages with the same name. They can be separated in the file system, I just did not know they will be compiled into one package. Thanks all the same! – Weixiang Guan Aug 21 '14 at 08:46
  • ooh..i missed that, my bad!!! – codingenious Aug 21 '14 at 08:57