0

How would you describe the very confusing difference between

  1. a protected instance member and
  2. a protected static member

in Java?

(A member can be either a method or a variable.)


Regarding 1 (protected instance member):

package a;

public class A {
    
    protected void methodInstanceProtected() { };
}

and

package b;

import a.A;

public class B extends A {
    
    public static void main(String[] args) {
        
        // instance:
        
        B b = new B();
        b.methodInstanceProtected(); // access via inheritance
        
        A a = new A();
        a.methodInstanceProtected(); // compiler error!
    }
}

The protected instance member can only be access via inheritance:

B b = new B();
b.methodInstanceProtected(); // compiles

It cannot be "seen" from the class B:

A a = new A();
a.methodInstanceProtected(); // compiles NOT

Regarding 2 (protected static member):

package a;

public class A {
    
    protected static void methodStaticProtected() { };
}

and

package b;

import a.A;

public class B extends A {
    
    public static void main(String[] args) {
                
        B.methodStaticProtected(); // acces via inheritance
        
        A.methodStaticProtected(); // compiles
    }
}

The first case is clear: Access via inheritance, as in protected instance member.

BUT: Why can the protected static member be seen from the class B, whereas protected instance member cannot (!) be seen from the same class B?


Even Oracle seems to find this so odd that they don't seem to mention or explain it: Controlling Access to Members of a Class

mrbela
  • 4,477
  • 9
  • 44
  • 79

0 Answers0