为什么我可以在测试中访问受保护的方法?

DP_*_*DP_ 4 java

假设我有这样一个类:

public class ClassA
{
    [...]

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

    [...]
}
Run Code Online (Sandbox Code Playgroud)

当我在IntelliJ Idea 13中编写单元测试时,当我写下类似的内容时,我不会遇到编译器错误:

public class ClassATest
{
    @Test
    public void test()
    {
        final ClassA objectUnderTest = new ClassA();

        objectUnderTest.methodIWantToTest(); // Why can I access a protected method here?
    }
}
Run Code Online (Sandbox Code Playgroud)

methodIWantToTest受到保护.为什么我可以在测试中访问它?

Jef*_*rey 12

因为类在同一个包中(即使是不同的文件夹).同一个包中的类以及子类可以访问受保护的方法.


wes*_*ton 5

这不是 junit 的奇怪之处,也不是与 ide 相关的任何事情。它只是protected在做什么protected呢,当你在同一个包中的类(想必你一定要哪个)。

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
Run Code Online (Sandbox Code Playgroud)

https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

这不同于其他语言的定义,protectedc#例如在protected仅指类,它的亚型。