简体   繁体   中英

Why can I access a protected method in a test?

Let's say I have a class like this:

public class ClassA
{
    [...]

    protected void methodIWantToTest()
    {
        [...]
    }

    [...]
}

When I a 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 is protected. Why can I access it in a test?

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

This is not a junit oddity or anything to do with the ide. It's just protected doing what protected does when you have the classes in the same package (which presumably you must).

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 languages definitions of protected such as c# for example where protected means only the class and it's subtypes.

Protected Access Modifier: Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM