I am reading an OCA and OCP book for java 7 certification, and I am trying to perform exercises using java 8, and I noticed something connected.
I have class Class1 as follows:
package cert;
public class Class1{
protected static void importantMethod(){
System.out.println("importantMethod() method of Class1 class TEST \n");
}
The modifiers of the importantMethod () method are protected by static , and the cert package , as you can see, and as explained in the book, I expect that another class from another package, in my case Class2 below, 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 .
Grade 2:
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 Class2
exam\Class2.java:7: error: importantMethod() has protected access in Class1
c1.importantMethod();
^
My question is, does the modifier change access to the access level for a class member?
source
share