1

I read a book for OOP and an example about 'protected' access modifier is strange for me.

Summary of example

  1. This example is to test how 'protected' reserved word effects to variables.
  2. ClassA has 2 protected variables (static / non-static)

    package a;
    
    public Class A {
    
        protected int a;
        protected static int b;
    }
    


  1. ClassB is derived from ClassA and located another package
  2. ClassB.test has a method to check accessibility (Cannot run)

    package b;
    
    public Class B extends ClassA {
    
        ClassA x = new ClassA();
    
        // [O] : Executable
        // [X] : Not-executable
        void test() {
    
            a = 1;   // [O] : Derived from ClassA
            b = 1;   // [O] : Derived from ClassA
    
            // [X] : a is protected, so only accessible within codes in derived class
            x.a = 1; // A) 
    
            // [O] : I don't know why it is executable
            x.b = 1; // B) 
        }
    }
    


Actually, b is 'protected' so I thought it cannot be accessed by instance variable like x.a = 1;
But it can be accessible with 'static' keyword. How can I understand for this?

Shortly A) is fine, but why is B) executable ?

Matt
  • 70,063
  • 26
  • 142
  • 172
niah
  • 83
  • 1
  • 8

1 Answers1

3

The static keyword means that variable belongs to the class itself instead of the objects of said class. You could replace your call to x.b with ClassA.b. Since ClassB extends ClassA, all protected static variables are accessible for all methods of ClassB at all time.