I am reading the book of OCA & OCP for java 7 certification and I am trying the exercises of the book with java 8 and I noticed something wired.
I have Class1 class as follows:
package cert;
public class Class1{
protected static void importantMethod(){
System.out.println("importantMethod() method of Class1 class TEST \n");
}
The modifiers of importantMethod() method are protected static and the package is cert as you may see, and as explained in the book I would expect that another class from another package, in my case Class2 shown bellow, can access the importantMethod() method only through inheritance, but it turned out that from Class2 I could access the importantMethod() method through an instance of Class1 as well.
Class2 class:
package exam;
import cert.Class1;
class Class2 extends Class1 {
public static void main(String[] args) {
Class1 c1 = new Class1();
c1.importantMethod();
}
}
If I remove the static modifier from Class1 it gives the expected error when trying to access the importantMethod() method from the Class2:
exam\Class2.java:7: error: importantMethod() has protected access in Class1
c1.importantMethod();
^
My question is, does a non access modifier change the level of access for a member of a class?
Everything is fine - that's how protected
access is meant to work. It's specified in JLS 6.6.2.1:
Let
C
be the class in which a protected member is declared. Access is permitted only within the body of a subclassS
ofC
.In addition, if
Id
denotes an instance field or instance method, then:
- [Irrelevant stuff as
Id
does not denote an instance field or instance method]
Your code is within the body of a subclass S
of C
(where S
is Class2
and C
is Class1
) so it's fine.
See more on this question at Stackoverflow