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?
public
– Positivestatic
doesn't change the level of access, but the type of access. – Pentastichnew Class1
, not aClass2
– Positive