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?

+3


source to share


3 answers


Because the classes are in the same package (even if they are different folders). Classes in the same package as well as subclasses can access protected methods.



+11


source


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.

+4


source


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.

0


source







All Articles