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?
}
}
Yes, you can declare an abstract method protected. If you do so you can access it from the classes in the same package or from its subclasses.
abstract methods have the same visibility rules as normal methods, except that they cannot be private .
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.
Notes: You cannot declare a class as protected . Only the methods or fields within a class can have this access modifier.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With