Abstract class. Why is my protected method publicly available?

Why can I access the method doStuff()in the main method below? Since it doStuff()is protected, I expect it to be accessed only TestClassImplementation.

public abstract class AbstractTestClass {
    protected void doStuff()
    {
        System.out.println("doing stuff ...");
    }
}

public class TestClassImplementation extends AbstractTestClass{

}

public class MyProgram {
    public static void main(String[] args) {
        TestClassImplementation test = new TestClassImplementation();
        test.doStuff(); //why can I access the doStuff() Method here?
    }
}
+4
source share
2 answers

It looks like the class MyProgramis in the same package of yours AbstractTestClass. If so, then it can get access to protectedand publicthe members of the classes in the same package.

Coverage in Java tutorials:

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

To fix this, simply move AbstractTestClassto another package. Similarly for other relevant classes.

Additional Information:

+11
source

Java protected , . .

+3

All Articles