Reputation: 1101
Why can I access the doStuff()
Method in the main method below? Since doStuff()
is protected, I would expect that only TestClassImplementation
has access to it.
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?
}
}
Upvotes: 5
Views: 5960
Reputation: 85779
Looks like MyProgram
class is in the same package of your AbstractTestClass
. If so, then it can access to protected
and public
members of the classes in the same package.
Covered 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
In order to fix this, just move the AbstractTestClass
to another package. Similar for other relevant classes.
More info:
Upvotes: 13
Reputation: 4992
In Java the keyword protected
includes access not only from subclasses, but actually the entire package. There is no way to prevent that.
Upvotes: 3