Does a static modifier change the access level of a class member in java?

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?

+6
source share
2 answers

Everything is in order - how protectedaccess works . It is specified in JLS 6.6.2.1 :

Let be the Cclass in which the protected member is declared. Access is allowed only inside the body of the subclass Sof C.

In addition, if Iddenotes an instance field or instance method, then:

  • [ Id ]

S of C ( S Class2 C is Class1), .

+3

, 2 importantMethod() 1

. Class1.importantMethod() . static, , .

1,

package exam;
import cert.Class1;
public class Class2 extends Class1 {

    public static void main(String[] args) {
        new Class2().importantMethod();
    }
}
+2

Source: https://habr.com/ru/post/1016467/


All Articles