Why can I access the protected method in the test?
Let's say I have a class like this:
public class ClassA
{
[...]
protected void methodIWantToTest()
{
[...]
}
[...]
}
When I write a unit test in IntelliJ Idea 13, I don't get compiler errors when I write something like:
public class ClassATest
{
@Test
public void test()
{
final ClassA objectUnderTest = new ClassA();
objectUnderTest.methodIWantToTest(); // Why can I access a protected method here?
}
}
methodIWantToTest
protected. Why can I access it in the test?
source to share
This is not unit weirdness or something to do with the idea. It just protected
does what it protected
does when you have classes in the same package (which you supposedly should).
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
This differs from other definitions of languages protected
, such as, c#
for example, where it protected
means only a class and its subtypes.
source to share
Protected access modifier: Variables, methods, and constructors that are declared protected in a superclass can only be accessed by subclasses of another package or any class in the package of a protected member class.
The Protected Access modifier cannot be applied to class and interfaces. Methods and fields can be declared protected, but methods and fields in an interface cannot be declared protected.
Protected access gives a subclass the ability to use a helper method or variable without allowing an unrelated class to try to use it.
source to share